Python中subprocess.run调用sd_namesp变量报语法错误如何解决?
你遇到的无效语法报错和subprocess.run调用变量的方式无关,错误出在sd_namesp变量的赋值行:sd_namesp = seccontent.get("name") + seccontent.get("ition") + str(seccontent.get("version")
这里str(seccontent.get("version")缺少了闭合的右括号,直接触发了语法校验失败。
你原本把sd_namesp直接作为列表元素传入largs的写法是完全正确的,不需要额外用f-string格式化,修正语法错误后即可正常运行。另外为了避免get方法获取不到对应键返回None时拼接字符串报错,可以给get方法补充默认空字符串的参数,优化后的代码如下:
for seccontent in sec_ver_data: # 补全str的闭合括号,给get方法加默认值避免None拼接报错 sd_namesp = seccontent.get("name", "") + seccontent.get("ition", "") + str(seccontent.get("version", "")) largs = ['java','-jar','cli.jar','n','-cf', config_path, '-r', seccontent.get("reg"), '-n', seccontent.get("name"), '-i', seccontent.get("sid"), '-f', sd_namesp] lresp = subprocess.run(largs, text=True, capture_output=True, check=True) print(lresp.stdout) print("end")
内容的提问来源于stack exchange,提问作者Suzana
相关产品推荐
相关产品推荐

