【问题标题】:Converting a file from .sam to .bam using python subprocess使用 python 子进程将文件从 .sam 转换为 .bam
【发布时间】:2015-05-29 19:52:33
【问题描述】:

我想首先说非常感谢任何帮助。我是 Python 和一般脚本的新手。我正在尝试使用一个名为 samtools view 的程序将文件从 .sam 转换为 .bam 我需要能够执行此 BASH 命令在 Python 中执行的操作:

samtools view -bS aln.sam > aln.bam   

我知道 BASH 命令像 | >

cmd = subprocess.call(["samtools view","-bS"], stdin=open(aln.sam,'r'), stdout=open(aln.bam,'w'), shell=True)

from subprocess import Popen

with open(SAMPLE+ "."+ TARGET+ ".sam",'wb',0) as input_file:
    with open(SAMPLE+ "."+ TARGET+ ".bam",'wb',0) as output_file: 
        cmd = Popen([Dir+ "samtools-1.1/samtools view",'-bS'],
            stdin=(input_file), stdout=(output_file), shell=True) 

在 Python 中,我仍然没有让 samtools 将 .sam 转换为 .bam 文件。我究竟做错了什么?

【问题讨论】:

    标签: python linux bash shell python-2.7


    【解决方案1】:

    Abukamel 是对的,但如果您(或其他人)想知道您的具体示例......

    您的第一次尝试并不算太远,只是一些小项目:

    1. 文件名应该用引号引起来
    2. samtools 从命名输入文件中读取,而不是从标准输入中读取
    3. 您不需要“shell=True”,因为您没有使用重定向等 shell 技巧

    所以你可以这样做:

    import subprocess
    subprocess.call(["samtools", "view", "-bS", "aln.sam"],
                    stdout=open('aln.bam','w'))
    

    您的第二个示例或多或少存在相同的问题,因此需要更改为:

    from subprocess import Popen
    with open('aln.bam', 'wb',0) as output_file: 
        cmd = Popen(["samtools", "view",'-bS','aln.sam'],
                    stdout=(output_file))
    

    【讨论】:

    • 非常感谢您的帮助和引导我完成整个过程。
    【解决方案2】:

    您可以通过 kwarg 'shell=True' 将执行传递给 shell

    subprocess.call('samtools view -bS aln.sam > aln.bam', shell=True)

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多