【问题标题】:How do I use a subprocess to run a shell program within a python loop?如何使用子进程在 python 循环中运行 shell 程序?
【发布时间】:2017-05-25 16:23:11
【问题描述】:
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                                     ^

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

如有任何帮助,我们将不胜感激

【问题讨论】:

  • 提示:-a 是 Python 变量吗?

标签: python bash shell loops subprocess


【解决方案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)和参数(例如 egg.txt)放在单独的列表元素中,而在 shell 中使用时需要引用或反斜杠转义的参数(例如包含空格的文件名或上面显示的 echo 命令)是单个列表元素。

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

【讨论】:

  • 啊哈,我会试试的。非常感谢!
猜你喜欢
  • 2011-05-22
  • 1970-01-01
  • 2022-07-16
  • 1970-01-01
  • 2019-05-02
  • 2018-08-13
  • 2011-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多