亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對齊文本文件python中的多個函數

對齊文本文件python中的多個函數

天涯盡頭無女友 2023-09-12 17:52:53
我正在嘗試根據用戶輸入將多個函數寫入文件。這里的問題是寫入文件的代碼沒有左對齊。也許缺少一些基本元素。這是代碼:import requestsG=input("Define Count")for k in range(0,G):perf=Gif k==0 :        string = """            ### RUN ####            def run():                d = collections.OrderedDict()                d['run']= 123,                return d            URL = "https://..../run"            headers  = {"Content-Type":"application/json",                        "Authorization": Token}            payload = json.dumps([run() for n in range(%s)])            resp = requests.post(URL, headers = headers ,data = payload))            if resp.status_code = 200:                print('Fail: ' + str(resp.status_code)+ str(resp.text))            else:                print('Pass' + str(resp.status_code)+ str(resp.text))                """            string = Template % (Perf)            with open(path, 'a') as f:                f.write(string)elif k==1:         string = """            ### STOP ####            def stop():                d = collections.OrderedDict()                d['STOP']= 123,                d['wait']=20                return d            URL = "https://..../stop"            headers  = {"Content-Type":"application/json",                        "Authorization": Token}            payload = json.dumps([stop() for n in range(%s)])            resp = requests.post(URL, headers = headers ,data = payload))            if resp.status_code = 200:                print('Fail: ' + str(resp.status_code)+ str(resp.text))            else:                print('Pass' + str(resp.status_code)+ str(resp.text))                """            string = Template % (Perf)            with open(path, 'a') as f:                f.write(string)  elfif k=.....當在循環中執行時,我期望寫入后的輸出文件,左對齊為:   def run():            ....            ....   def stop():           ....           ....   def wait():           ....不知道為什么我會出現不規則的縮進。請幫助我
查看完整描述

1 回答

?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

我發現您共享的代碼存在幾個主要邏輯問題。


所有條件均表示為 = 而不是 ==

    # For Example,

    if k=0 :   # This is wrong

    if k == 0: # This is correct for the comparison

我在您的代碼中沒有看到正確的縮進。希望是復制粘貼問題。

對于您的邏輯,您可以創建一個出色的函數指針映射。例如

def func1():

  print('func1')


def func2():

  print('func2')


funcs_map = {}

funcs_map[1] = func1

funcs_map[2] = func2



for i in range(10);

  if i in funcs_map.keys():

      func_ptr = funcs_map[i]

      func_ptr()


# The above approach would be easy to manage to it will help you debug

# instead of hardcoding functionality within string. 

祝你好運,看看上述建議是否解決了您的問題。


查看完整回答
反對 回復 2023-09-12
  • 1 回答
  • 0 關注
  • 100 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號