我有这个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
我如何做对吗?
答案 0 :(得分:4)
默认情况下,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.py < input > outfile
。)
from subprocess import call
script="python 1.py".split()
with open("input", "r") as input:
with open("outfile", "w") as output:
call(script, stdin=input, stdout=output)
答案 1 :(得分:1)
与将|
和>
视为特殊重定向符号的shell不同,Python call()
认为它们是正常的,并且传递给普通参数cat
。您可以考虑使用其他方法(如os.system
:
import os
os.system("cat input | python 1.py > outfile")
从Running a command completely indepenently from script转发的答案。