替换 ipython 的系统 shell 命令中的循环变量

replace loop variable in system shell command of ipython

我想遍历(样本名称)列表,并使用 ipython 的系统 shell 命令(“!”)对每个样本重复相同的命令。我以前这样做没有问题,但在此特定代码下不断收到 SyntaxError。如果您知道哪里出了问题,请告诉我 - 谢谢!

这里是示例代码(现实中还有更多示例):

samples = ["ERR007200", "ERR007204", "ERR007208"]
def remove_ambMap():
    !samtools view -q 20 -b home/pathToFile/{samp}.realn.bam | samtools sort - {samp}
for samp in samples:
    remove_ambMap()

请注意,samtools 是一个位于 $PATH 中的程序,如果我执行指定文件路径的命令,它就可以工作 - 抱歉,这将无法重现,因为您需要安装该程序,这些是大量基因组文件 - 我希望有人能够发现问题所在!

对于此类任务,您需要使用 subprocess 模块;这 最简单的方法是将 call 方法与 shell=True:

一起使用
from subprocess import call

def remove_ambMap(samp):
    call('samtools view -q 20 -b home/pathToFile/{samp}.realn.bam '
         '| samtools sort - {samp}'.format(samp=samp), shell=True)

for samp in samples:
    remove_ambMap(samp)