中的变量子流程调用运行时命令行上无法识别的命令,特别是文件

2024-10-02 12:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图通过下面的命令子流程调用()

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']

这是正确的文件输入。你知道吗

插入打印出来的命令(当然没有逗号和引号)工作正常,因此没有问题。你知道吗

我以前对使用变量列表没有异议子流程调用()任何帮助都将不胜感激!你知道吗

完整代码:

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)

Tags: 文件nameimport命令samcount流程out
1条回答
网友
1楼 · 发布于 2024-10-02 12:24:33

>是shell语法。它是一个文件的标准输出。这意味着您需要在shell中使用subprocess.call(command, shell=True)运行命令

但由于这需要仔细引用所有参数以防止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

相关问题 更多 >

    热门问题