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

标签 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 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/

相关文章:

python - 尝试解析 Python 中的旧语法

linux - Shell嵌套for循环和字符串比较

linux - 尝试从文本文件中获取实例 ID

python - Keras flow_from_dataframe 给出 0 个图像

python - 使用另一个数据框 pandas 中的相同内容重命名每 2 列

python - 基于训练集的 OpenCV (Python) 图像分类

java - 使用 Hadoop Streaming 时通过脚本运行 Java 应用程序 : java. lang.NoClassDefFoundError

python - flask_mail 消息实例不是 JSON 可序列化的

linux - 查找字符串并将替换的字符串存储在其他文件 shell 脚本中

linux - 在 fish shell 中定义一个别名