python子流程运行时使用单个字符串,但不使用字符串列表

2024-06-01 01:08:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图使用子流程模块中的运行方法,从Python脚本启动一个带有命令行选项的命令行程序

我的命令定义为指定程序和选项的字符串列表,如下所示(其中pheno_fpconstruction_fp是表示系统中文件路径的字符串,exe是表示我正在运行的程序的文件路径的字符串):

    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)

如果我正确理解了文档,建议使用前一种方法,但我不明白为什么它不起作用。我很确定它的格式与文档中的示例相同,所以我有点困惑。有什么想法吗


Tags: 文件方法字符串命令行命令路径程序cmd
2条回答

将每个参数与其值拆分,如下所示:

step1_cmd = [exe, 
             " step",
             "1",
             " p",
             str(pheno_fp),  # if it isn't a string already
             " b",
             "1000",
             " o",
             str(construction_fp) + "dpw_leaveout"
]

因为在传递参数列表时,每个部分都用空格分隔,包括选项及其值

对这种行为的解释是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']) 

相关问题 更多 >