subprocess.call命令中的变量在运行时无法在命令行中识别,具体是文件

时间:2018-02-01 18:54:50

标签: python linux subprocess

我试图通过subprocess.call()

传递以下命令
command = ['htseq-count', '-t', 'miRNA', '-i', 'Name', f, annot_file, out_file]

运行时,我收到htseq-count至少需要2个参数的通知,这意味着它没有意识到命令中有输入文件。

在运行时打印命令会显示以下内容:

['htseq-count', '-t', 'miRNA', '-i', 'Name', 'KDRD1XX_ACAGTG_L001_R1_001_trimmedaligned.sam', 'hsa.gff3', 'KDRD1XX.htseq.sam']

哪个是正确的文件输入。

插入打印出的命令(当然没有逗号和引号)工作正常,所以没有问题。

在使用subprocess.call()之前我没有使用变量列表的问题,所以任何帮助都将不胜感激!

完整代码:

import sys
import subprocess
import os

annot_file='hsa.gff3'
dirs= os.listdir('.')

for f in dirs:
    if f.endswith("_trimmedaligned.sam"):

        of=f.split('_')
        outfile='>'+of[0]+'.htseq.sam'
        command=['htseq-count','-t','miRNA','-i','Name',f,annot_file, out_file] 
        #print(command)
        subprocess.call(command)

1 个答案:

答案 0 :(得分:1)

>是shell语法。它是文件的redirection标准输出。这意味着您需要使用subprocess.call(command, shell=True)

在shell中运行该命令

但是因为那需要仔细引用所有参数来阻止来自shell command injection,我建议运行命令并保存Python的输出:

for f in dirs:
    if not f.endswith("_trimmedaligned.sam"):
        continue

    of=f.split('_')
    outfile=of[0]+'.htseq.sam'
    command = [
        'htseq-count',
        '-t',
        'miRNA',
        '-i',
        'Name',
        f,
        annot_file,
    ]

    process = subprocess.Popen(command,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)

    stdout, stderr = process.communicate()

    # Don't miss to check the exit status
    if process.returncode != 0:
        print("Ooops! Something went wrong!")

    # Write output file
    with open(out_file, 'wb') as fd:
        fd.write(stdout)

PS:以上示例适用于小输出文件。它将所有输出缓冲在内存中。如果输出文件达到合理的大小,您可以使用poll()流式传输命令,如下所述:https://stackoverflow.com/a/2716032/171318