我有这个 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.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)
关于python - 使用 call() 执行 cat,在 python 中使用管道和重定向输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23888628/