python - subprocess.Popen 解析命令列表时出现问题;管道未正确发送

标签 python

当我在解释器中运行以下命令时

infile_intersect = subprocess.Popen(['cut', '-f', '1,2,3,4,5', infile, r'|', 'intersectBed', '-a', 'stdin', '-b', bound_motif, '-wo', r'|', 'sort', '-k', '1,1', '-k', '2,2n', '|uniq'], stdout=subprocess.PIPE).communicate()

我收到错误 cut: invalid option -- a 但当我对列表进行空格连接时,它看起来很好

>>> ' '.join(['cut', '-f', '1,2,3,4,5', infile, r'|', 'intersectBed', '-a', 'stdin', '-b', bound_motif, '-wo', r'|', 'sort', '-k', '1,1', '-k', '2,2n', '|uniq'])
'cut -f 1,2,3,4,5 test.bed | intersectBed -a stdin -b ENCODE.tf.bound.union.bed -wo | sort -k 1,1 -k 2,2n |uniq'

看起来管道没有正确发送,但我不确定为什么

最佳答案

这不是使用子进程进行管道传输的方式,使用带有列表输入表单的 | 是无效的。您应该将完整的字符串传递给它并使用 shell=True 或像我在下面的示例中所做的那样使用管道:

>>> import subprocess
>>> p = subprocess.Popen(['cat', 'abc1'], stdout=subprocess.PIPE)
>>> p1 = subprocess.Popen(['uniq', '-c'], stdin=p.stdout, stdout=subprocess.PIPE)
>>> print p1.communicate()[0]
      3 word1
      1 word3
      1 word4
      1 word5

使用字符串和shell=True

>>> print subprocess.Popen('cat abc1 | uniq -c', shell=True,
                                            stdout=subprocess.PIPE).communicate()[0]
      3 word1
      1 word3
      1 word4
      1 word5

来自docs :

Warning Invoking the system shell with shell=True can be a security hazard if combined with untrusted input.

关于python - subprocess.Popen 解析命令列表时出现问题;管道未正确发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434039/

相关文章:

java - 将剪辑路径信息添加到图像

python - 带图标的 QSlider

python - 用Python制作一个电子邮件函数

python pandas - 检查列中的部分字符串是否存在于其他列中

python - Pycharm:为运行 manage.py 任务设置环境变量

python - 如何为目录中的每个文件添加随机数? (初学者)

python - 如何将 int 转换为 4 字节十六进制

python - 是否有单一的匹配和替换功能?

python - 如何按列对 xls 文件进行排序并使用 python 将其写入整行的另一个文件?

python - 有关编写构建方案的文档