【问题标题】:Python subprocess() reading file in bashPython subprocess()在bash中读取文件
【发布时间】:2022-01-05 20:17:02
【问题描述】:

我有一个用于文件的 shell 命令,如下所示:

filename="/4_illumina/gt_seq/gt_seq_proccessor/200804_MN01111_0025_A000H35TCJ/fastq_files/raw_data/200804_MN01111_0025_A000H35TCJ.demultiplex.log"

assembled_reads=$(cat $filename | grep -i " Assembled reads ...................:" | grep -v "Assembled reads file...............:")

现在我正在尝试在 python 环境中使用子进程运行它:

task = subprocess.Popen("cat $filename | grep -i " Assembled reads ...................:" | grep -v "Assembled reads file...............:"", shell=True, stdout=subprocess.PIPE)
p_stdout = task.stdout.read()
print (p_stdout)

这不起作用,因为我无法将文件名变量从 python 解析到 shell,并且我编写 grep 命令的方式可能存在语法错误。

有什么建议吗?

【问题讨论】:

  • 引号不平衡。
  • 谢谢,刚刚编辑好了
  • 在 Python task = subprocess.Popen(f"cat ${filename} | ... 的第一行的开头尝试过(然后是该行的其余部分),您也使用了上面在 Python 中发布的文件名分配?你有机会在你的机器上使用 IPython 或 Jupyter 吗?在这些情况下,您可以使用更简单的选项将 bash 与 Python 混合。
  • 引号还是不平衡。您必须使用 "\" 转义内部 "s。
  • 这工作task = subprocess.Popen(f"cat {filename}", shell=True,stdout=subprocess.PIPE)

标签: python python-3.x shell subprocess


【解决方案1】:

我会考虑在 python 中进行所有的阅读和搜索,也许会重新考虑你想要实现的目标,但是:

在外壳中:

$ export filename=/tmp/x-output.GOtV 

在 Python 中(注意访问$filename 并在命令中混合引号,我还使用自定义 grep 命令来简化一些事情):

import os
import subprocess
tmp = subprocess.Popen(f"cat {os.environ['filename']} | grep -i 'x'", shell=True, stdout=subprocess.PIPE)
data = tmp.stdout.read()
print(data)

虽然可行,但解决方案......不是我认为的干净代码。

【讨论】:

    【解决方案2】:

    此代码似乎无需外部工具即可解决您的问题。

    filename="/4_illumina/gt_seq/gt_seq_proccessor/200804_MN01111_0025_A000H35TCJ/fastq_files/raw_data/200804_MN01111_0025_A000H35TCJ.demultiplex.log"
    for line in open(filename):
        if "Assembled reads" in line and "Assembled reads file" not in line:
            print(line.rstrip())
    

    【讨论】:

    • 谢谢,我决定采用pythonic方式!
    猜你喜欢
    • 2012-09-28
    • 2019-09-27
    • 2012-03-27
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2019-05-24
    相关资源
    最近更新 更多