在Python脚本中执行shell命令时传入变量参数失败如何解决?
问题根因
你代码中定义的path和save是Python变量,直接写在单引号命令串中的$save、$path是shell的变量引用语法,当前执行的shell环境中并没有声明这两个变量,自然无法获取到Python中定义的变量值,导致引用失效。
解决方案
方案1:Python字符串格式化注入变量(保留shell=True写法)
Python3.6及以上版本可以直接用f-string把变量值插入到命令字符串中,注意路径外侧加双引号避免路径包含空格时出错,示例代码:
from subprocess import call path='/home/ranim/Documents/mmdet/media/Page_00287_jpg.rf.6a823c5ce3894f223a0e8f4ec20b11b2/article1' save='/home/ranim/Documents/mmdet/media/Page_00287_jpg.rf.6a823c5ce3894f223a0e8f4ec20b11b2/article1/annotations.json' call(f'python "/home/ranim/Documents/mmdet/mmdetection/tools/test.py" \ "/home/ranim/Documents/mmdet/models/second_model_conf.py" \ "/home/ranim/Documents/mmdet/models/second_model_checkpoint.pth" \ --cfg-options data.test.ann_file="{save}" \ data.test.img_prefix="{path}" \ --format-only \ --options "jsonfile_prefix=path"', shell=True)
方案2:列表传参(更推荐,无需开启shell=True)
直接把命令拆分为参数列表传入call方法,无需处理字符串转义,也规避了shell=True带来的命令注入安全风险,示例代码:
from subprocess import call path='/home/ranim/Documents/mmdet/media/Page_00287_jpg.rf.6a823c5ce3894f223a0e8f4ec20b11b2/article1' save='/home/ranim/Documents/mmdet/media/Page_00287_jpg.rf.6a823c5ce3894f223a0e8f4ec20b11b2/article1/annotations.json' call([ "python", "/home/ranim/Documents/mmdet/mmdetection/tools/test.py", "/home/ranim/Documents/mmdet/models/second_model_conf.py", "/home/ranim/Documents/mmdet/models/second_model_checkpoint.pth", "--cfg-options", f"data.test.ann_file={save}", f"data.test.img_prefix={path}", "--format-only", "--options", "jsonfile_prefix=path" ])
内容的提问来源于stack exchange,提问作者Firas Kedidi
相关产品推荐
相关产品推荐

