【问题标题】:Using python subprocess.call for writing count of fasta sequences to file使用 python subprocess.call 将 fasta 序列的计数写入文件
【发布时间】:2016-04-25 13:06:37
【问题描述】:

我有超过 14000 个 fasta 文件,我只想保留那些包含 5 个序列的文件。我知道我可以使用以下 bash 命令来获取单个 fasta 文件中的序列数:

grep -c "^>" filename.fasta

所以我的方法是将每个文件中的文件名和序列数写入一个文本文件,然后我可以使用它来仅隔离我想要的序列。要对这么多文件运行 grep 命令,我使用的是 subprocess.call:

import subprocess
import os


with open("five_seqs.txt", "w") as f:
    for file in os.listdir("/Users/vivaksoni1/Downloads/DA_CDS/fasta_files"):
        f.write(file),
        subprocess.call(["grep", "-c", "^>", file], stdout = f)

我的部分问题是 grep 命令是“^>”,但是 subprocess 要求每个参数都有自己的引号。当我本质上是作为参数输入时,如何使用“^>”:“”^>“”。

另外,我必须在 f.write(file) 之后添加 f.write("\n") 吗?目前我的输出只是一个文本文件,每个条目彼此相邻,子进程命令只是将每个文件名打印到终端并声明没有找到这样的文件:

grep: MZ23900789.fasta: 没有这样的文件或目录

【问题讨论】:

  • 您是否尝试过:shell=True 上的subprocess.call()?示例:subprocess.call(["grep", "-c", "^>", file], stdout=f, shell=True)
  • 嗨,不幸的是,我确实尝试过这个但没有成功。 grep 命令仍然没有写入文件,我正在为每个文件将这个输出发送到终端:用法:grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C[num]] [ -e 模式] [-f 文件] [--binary-files=value] [--color=when] [--context[=num]] [--directories=action] [--label] [--line -buffered] [--null] [pattern] [file ...]
  • 获取一个文件,任何只是为了测试一下:grep -c '^>' fasta_file.. 如果它有效,然后尝试:subprocess.call(["grep", "-c", "'^>'", file], stdout=f, shell=True) 否则有其他问题,请随时剖析并测试调用. pdb 是你的朋友 -- ipdb 是你最好的朋友
  • 引用python引号内的参数。 '"^>"'"'^>'".
  • 我尝试在 python 引号内引用参数,但得到与以前相同的终端响应。逐行查看我的代码后,我仍然无法破译问题的根源。

标签: python linux bash subprocess fasta


【解决方案1】:

尝试以下代码,它应该适用于您的示例。它将写入文件名加上制表符分隔符和序列数(即> 字符)。 使用Popencommunicate 在处理输出时提供了更好的灵活性。在 Ubuntu 上测试。

import subprocess
import os

fasta_dir = "/Users/vivaksoni1/Downloads/DA_CDS/fasta_files/"

with open("five_seqs.txt", "w") as f:
    for file in os.listdir(fasta_dir):
        f.write(file + '\t')
        grep = subprocess.Popen(["grep", "-c", "^>", fasta_dir + file], stdout = subprocess.PIPE)
        out, err = grep.communicate()
        f.write(out + '\n')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    相关资源
    最近更新 更多