python - subprocess.call 命令中的变量在运行时无法在命令行上识别,特别是文件

标签 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)

最佳答案

>是 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

关于python - subprocess.call 命令中的变量在运行时无法在命令行上识别,特别是文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48569879/

相关文章:

python - 如何解除pycharm文件中的锁定?

linux - 在插入模式下移至 VI 中当前行的行尾或行首

regex - 使用 linux 重新格式化被屠杀的文本

python - 为什么 subprocess.Popen 不起作用

python - mkstemp 打开太多文件

python子进程多个stdin.write和stdout.read

python - 如何判断两个字符串是否有共同的字符部分?--Python

python - 如何在 tf.layers.keras.Conv2D 中初始化常量偏差?

python - 在 Python 中初始化/创建/填充字典的字典

linux - 用于反转文件中的行并将其存储在另一个文件中的 UNIX 命令