使用call()执行cat,使用管道和python中的重定向输出

使用call()执行cat,使用管道和python中的重定向输出,python,shell,Python,Shell,我有一个shell命令: cat input | python 1.py > outfile input是一个包含值的文本文件 3 1 4 5 而1.py是: t = int(raw_input()) while t: n = int(raw_input()) print n t -= 1 当我进入终端时,它运行良好 但是,当我使用以下代码从Python运行此代码时: from subprocess import call script = "cat inp

我有一个shell命令:

cat input | python 1.py > outfile
input
是一个包含值的文本文件

3
1
4
5
1.py
是:

t = int(raw_input())

while t:
    n = int(raw_input())
    print n
    t -= 1
当我进入终端时,它运行良好

但是,当我使用以下代码从Python运行此代码时:

from subprocess import call
script = "cat input | python 1.py > outfile".split()
call(script)
我得到:

3
1
4
5

cat: |: No such file or directory
cat: python: No such file or directory
t = int(raw_input())

while t:
    n = int(raw_input())
    print n
    t -= 1
cat: >: No such file or directory
cat: outfile: No such file or directory

cat: |: No such file or directory
cat: python: No such file or directory
cat: >: No such file or directory
cat: outfile: No such file or directory

如何正确执行?

默认情况下,
call
的参数直接执行,而不是传递给shell,因此不会处理管道和IO重定向。改用
shell=True
和单个字符串参数

from subprocess import call
script = "cat input | python 1.py > outfile"
call(script, shell=True)
但是,最好让Python自己处理重定向,而不涉及shell。(请注意,
cat
此处是不必要的;您可以使用
python 1.pyoutfile


与shell中的
|
被视为特殊重定向符号不同,Python的
调用()
将它们视为正常的,并将它们与正常参数一起传递给
cat
。您可以考虑通过shell调用命令,如“代码>操作系统。系统< /代码>:

import os
os.system("cat input | python 1.py > outfile")

答案转发自。

Python文档本身更喜欢
子流程
模块,而不是使用
os.system
。如果我的命令中有如下偏执语句,该怎么办:“cat?”
import os
os.system("cat input | python 1.py > outfile")