首页 > 解决方案 > 使用 python 子进程调用处理通配符扩展

问题描述

我正在调用此函数并%s*silent用于读取具有以下格式名称的文件:name.number.silent.

我得到了这个名字,start_model.split('/')[-1].split('.')[0]所以不用担心。

这显然是行不通的,因为这些命令实际上从未传递给 shell。如果我要使用 glob,我该如何修改我的代码来做我在下面做的事情?

from subprocess import call

def fragment_score(rosetta_path, silent_input_and_score_output, start_model):
    call([rosetta_path,
          '-mode score', 
          '-in::file::silent', '%s/%s*silent' % (silent_input_and_score_output, start_model.split('/')[-1].split('.')[0]),
          '-scorefile', '%s/scores1' % silent_input_and_score_output,
          '-n_matches', '50'])

标签: pythonsubprocessglob

解决方案


使用Pythonglob模块生成 glob 结果列表,并将其拼接到参数列表中的相同位置,否则 shell 将用关联匹配列表替换 glob 表达式:

from subprocess import call
from glob import glob

def fragment_score(rosetta_path, silent_input_and_score_output, start_model):
    glob_exp = '%s/%s*silent' % (silent_input_and_score_output, start_model.split('/')[-1].split('.')[0])
    glob_results = glob(glob_exp)
    call([rosetta_path,
          '-mode score', 
          '-in::file::silent'
         ] + glob_results + [
          '-scorefile', '%s/scores1' % silent_input_and_score_output,
          '-n_matches', '50'])

在当前的 Python 3.x 中,有一些语法使它更自然:

    call([rosetta_path,
          '-mode score', 
          '-in::file::silent',
          *glob_results,
          '-scorefile', '%s/scores1' % silent_input_and_score_output,
          '-n_matches', '50'])

推荐阅读