我正在尝试根据用户输入将多个函数写入文件。这里的问题是写入文件的代码没有左对齐。也许缺少一些基本元素。这是代码: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
提交
取消