如何使用子进程在python循环中运行shell程序?

时间:2017-05-25 16:23:11

标签: python bash shell loops subprocess

num_of_files = 12
pair_count = 1
while pair_count < num_of_files:
    for root, dirs, all_files in os.walk(indir):
        read1 = all_files[pair_count]
        pair_count += 1
        read2 = all_files[pair_count]
        print(read1, read2)
        pair_count += 1
        process = subprocess.Popen
(cutadapt -a AATGATACGGCGACCACCGAGATCTACACGCCTCCCTCGCGCCATCAG
 -o out1.fastq -p out.2fastq read1 read2, shell=True, stdout=subprocess.PIPE)
if pair_count > num_of_files:
        break

我似乎在使用python循环中的cutadapt shell脚本时遇到了麻烦。运行时出现以下错误消息:

process = subprocess.Popen(cutadapt -a AATGATACGGCGACCACCGAGATCTACACGCCTCCCTCGCGCCATCAG 
-o out1.fastq -p out.2fastq read1 read2, shell=True, stdout=subprocess.PIPE)

                      SyntaxError: invalid syntax                                     ^

错误表示字符串结束...我不确定这可能是什么语法错误。

对此有任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

从文档中看,subprocess.Popen的参数应该是字符串或字符串列表。

subprocess.Popen(["cutadapt", "-a", "AATGATACGGCGACCACCGAGATCTACACGCCTCCCTCGCGCCATCAG", "-o", "out1.fastq", "-p", "out.2fastq", "read1", "read2"], shell=True, stdout=subprocess.PIPE)

提供所需的电话?

来自文档:

>>> import shlex, subprocess
>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

特别注意,由shell中的空格分隔的选项(例如-input)和参数(例如eggs.txt)位于单独的列表元素中,而在shell中使用时需要引用或反斜杠转义的参数(例如包含空格的文件名或上面显示的echo命令)是单个列表元素。

https://docs.python.org/2/library/subprocess.html#popen-constructor