我正在嘗試根據用戶輸入將多個函數寫入文件。這里的問題是寫入文件的代碼沒有左對齊。也許缺少一些基本元素。這是代碼: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.
祝你好運,看看上述建議是否解決了您的問題。
添加回答
舉報
0/150
提交
取消