当我在解释器中运行以下命令时
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/