【问题标题】:using call() to execute cat, with pipes and redirected output in python使用 call() 执行 cat,在 python 中使用管道和重定向输出
【发布时间】:2014-05-27 11:48:10
【问题描述】:

我有这个 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

我怎样才能做到正确?

【问题讨论】:

    标签: python shell


    【解决方案1】:

    默认情况下,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)
    

    【讨论】:

    • 如果我的命令中有括号,如下所示:'cat bal_train.csv'
    【解决方案2】:

    |> 被视为特殊重定向符号的shell 不同,Python 的call() 将它们视为正常的,并与cat 的正常参数一样传递。您可以考虑通过 shell 使用其他方法调用命令,例如 os.system:

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

    答案来自Running a command completely indepenently from script

    【讨论】:

    • Python 文档本身更喜欢使用subprocess 模块而不是使用os.system
    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2014-12-11
    • 2018-05-15
    • 1970-01-01
    • 2020-05-08
    相关资源
    最近更新 更多