python subprocess 运行 适用于单个字符串但不适用于字符串列表
python subprocess run works with single string but not list of strings
我正在尝试使用 运行 方法从我的 Python 脚本启动一个命令行程序=28=]子进程模块。
我的命令被定义为指定程序和选项的字符串列表,如下所示(其中 pheno_fp
和 construction_fp
是代表我系统中文件路径的字符串,而 exe
是一个代表程序文件路径的字符串 运行ning):
step1_cmd = [exe,
"--step 1",
"--p " + pheno_fp,
"--b 1000",
"--o " + construction_fp + "dpw_leaveout"]
不工作 - 当我尝试以下操作时,我想要 运行 的程序已启动但我指定的命令被错误解释,因为程序退出错误提示“使用 --o 标志指定输出文件路径”:
test1 = subprocess.run(step1_cmd)
工作 - 当我尝试以下操作时,程序正确执行,这意味着所有参数都按预期解释:
test1 = subprocess.run(" ".join(step1_cmd), shell=True)
如果我对文档的理解正确,前一种方法是推荐的用法,但我不明白为什么它不起作用。我很确定它的格式与文档中的示例相同,所以我有点难过。有什么想法吗?
将每个参数与其值分开,如下所示:
step1_cmd = [exe,
"--step",
"1",
"--p",
str(pheno_fp), # if it isn't a string already
"--b",
"1000",
"--o",
str(construction_fp) + "dpw_leaveout"
]
因为传递参数列表时,每个部分都用space分隔,选项及其值
对此行为的解释是 here:
args is required for all calls and should be a string, or a sequence
of program arguments. Providing a sequence of arguments is generally
preferred, as it allows the module to take care of any required
escaping and quoting of arguments (e.g. to permit spaces in file
names).
示例:序列
l = ['ls', '-l tmp']
报错
subprocess.run(l)
ls: illegal option --
这是因为 subprocess
(这是对 Popen
的调用)正在尝试 运行 ls "-l tmp"
.
定义参数序列的正确方法是将它们分开,以便正确引用它们
subprocess.run(['ls', '-l', 'tmp'])
我正在尝试使用 运行 方法从我的 Python 脚本启动一个命令行程序=28=]子进程模块。
我的命令被定义为指定程序和选项的字符串列表,如下所示(其中 pheno_fp
和 construction_fp
是代表我系统中文件路径的字符串,而 exe
是一个代表程序文件路径的字符串 运行ning):
step1_cmd = [exe,
"--step 1",
"--p " + pheno_fp,
"--b 1000",
"--o " + construction_fp + "dpw_leaveout"]
不工作 - 当我尝试以下操作时,我想要 运行 的程序已启动但我指定的命令被错误解释,因为程序退出错误提示“使用 --o 标志指定输出文件路径”:
test1 = subprocess.run(step1_cmd)
工作 - 当我尝试以下操作时,程序正确执行,这意味着所有参数都按预期解释:
test1 = subprocess.run(" ".join(step1_cmd), shell=True)
如果我对文档的理解正确,前一种方法是推荐的用法,但我不明白为什么它不起作用。我很确定它的格式与文档中的示例相同,所以我有点难过。有什么想法吗?
将每个参数与其值分开,如下所示:
step1_cmd = [exe,
"--step",
"1",
"--p",
str(pheno_fp), # if it isn't a string already
"--b",
"1000",
"--o",
str(construction_fp) + "dpw_leaveout"
]
因为传递参数列表时,每个部分都用space分隔,选项及其值
对此行为的解释是 here:
args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).
示例:序列
l = ['ls', '-l tmp']
报错
subprocess.run(l)
ls: illegal option --
这是因为 subprocess
(这是对 Popen
的调用)正在尝试 运行 ls "-l tmp"
.
定义参数序列的正确方法是将它们分开,以便正确引用它们
subprocess.run(['ls', '-l', 'tmp'])