如何在python中调用一系列bash命令并存储输出

时间:2015-07-13 22:51:22

标签: python linux bash shell sed

我正在尝试在Python中运行以下bash脚本并存储读取列表输出。我希望存储为python列表的读取列表是当前目录中以* concat_001.fastq结尾的所有文件的列表。

我知道在python中这样做可能更容易(即

import os
readlist = [f for f in os.listdir(os.getcwd()) if f.endswith("concat_001.fastq")]
readlist = sorted(readlist)

然而,这是有问题的,因为我需要Python来完全排序列表,就像bash一样,我发现bash和Python按照不同的顺序排序某些东西(例如Python和bash处理大写和非大写的东西)不同 - 但是当我尝试

readlist = np.asarray(sorted(flist, key=str.lower))

我仍然发现以ML_和M_开头的两个文件用bash和Python以不同的顺序排序。因此尝试通过Python运行我的精确bash脚本,然后在我后续的Python代码中使用用bash生成的排序列表。

input_suffix="concat_001.fastq"
ender=`echo $input_suffix | sed "s/concat_001.fastq/\*concat_001.fastq/g" `
readlist="$(echo $ender)"

我试过了

proc = subprocess.call(command1, shell=True, stdout=subprocess.PIPE)
proc = subprocess.call(command2, shell=True, stdout=subprocess.PIPE)
proc = subprocess.Popen(command3, shell=True, stdout=subprocess.PIPE)

但我得到:subprocess.Popen对象位于0x7f31cfcd9190

另外 - 我不明白subprocess.call和subprocess.Popen之间的区别。我试过了两个。

谢谢, 露丝

1 个答案:

答案 0 :(得分:0)

所以你的问题有点令人困惑,并不能完全解释你想要什么。但是,我会尝试提供一些建议,以帮助您更新它,或者在我的努力中,回答它。

我将假设以下内容:您的python脚本传递给命令行'input_suffix',并且您希望您的python程序在外部脚本完成时接收'readlist'的内容。

为了让我们的生活更简单,让事情变得更复杂,我会制作以下bash脚本来包含你的命令:

<强> script.sh

#!/bin/bash
input_suffix=$1
ender=`echo $input_suffix | sed "s/concat_001.fastq/\*concat_001.fastq/g"`
readlist="$(echo $ender)"
echo $readlist

您将执行此操作为script.sh "concat_001.fastq",其中$ 1接受在命令行上传递的第一个参数。

要使用python执行外部脚本,正如您正确找到的那样,您可以使用子进程(或另一个响应,os.system指出 - 尽管建议使用子进程)。

文档告诉您subprocess.call

  

“等待命令完成,然后返回returncode属性。”

那个

  

“对于不能满足您需求的更高级用例,请使用基础Popen接口。”

鉴于你想将bash脚本的输出传递给你的python脚本,让我们按照文档的建议使用Popen。当我发布其他stackoverflow答案时,它可能如下所示:

import subprocess
from subprocess import Popen, PIPE

# Execute out script and pipe the output to stdout
process = subprocess.Popen(['script.sh', 'concat_001.fastq'], 
                           stdout=subprocess.PIPE, 
                           stderr=subprocess.PIPE)

# Obtain the standard out, and standard error
stdout, stderr = process.communicate()

然后:

>>> print stdout
*concat_001.fastq
相关问题