Skip to main content
 首页 » 编程设计

python之将未知长度的选项传递给子进程

2025年05月04日9yyy_WW

这是我现有的(非功能性)代码。

def call_GM(sourcefile): 
    source = os.path.splitext(sourcefile) 
    outfile = '"' + source[0] + '_straightened' + source[1] + '"' 
    options = ('convert', '-auto-orient', sourcefile, outfile) 
    command = 'gm' 
    subprocess.call([command, options]) 

鉴于“选项”的长度并不总是固定的,我如何正确传递其内容?这是最简单的示例,但实际上我有类似的代码调用几个不同的命令。

请您参考如下方法:

将命令作为平面列表或元组传递:

def call_GM(sourcefile): 
    source = os.path.splitext(sourcefile) 
    outfile = '"' + source[0] + '_straightened' + source[1] + '"' 
    options = ['convert', '-auto-orient', sourcefile, outfile] 
    command = 'gm' 
    subprocess.call([command] + options) 

注意:将 options 修改为列表,因为 list + tuple 是不允许的。