Python:执行shell命令

use*_*714 1 python subprocess

我需要这样做:

paste file1 file2 file3 > result
Run Code Online (Sandbox Code Playgroud)

我的python脚本中有以下内容:

from subprocess import call

// other code here.

// Here is how I call the shell command

call ["paste", "file1", "file2", "file3", ">", "result"])
Run Code Online (Sandbox Code Playgroud)

不幸的是我收到此错误:

paste: >: No such file or directory.

任何帮助都会很棒!

Ale*_*lli 5

如果你明智地决定不使用shell,你需要自己实现重定向.

https://docs.python.org/2/library/subprocess.html上的文档警告您不要使用管道 - 但是,您不需要:

import subprocess
with open('result', 'w') as out:
    subprocess.call(["paste", "file1", "file2", "file3"], stdout=out)
Run Code Online (Sandbox Code Playgroud)

应该没问题.


Joh*_*024 5

有两种方法。

  1. 用途shell=True

    call("paste file1 file2 file3 >result", shell=True)
    
    Run Code Online (Sandbox Code Playgroud)

    重定向>是Shell的功能。因此,您只能在使用shell:时访问它shell=True

  2. 保留shell=False并使用python执行重定向:

    with open('results', 'w') as f:
        subprocess.call(["paste", "file1", "file2", "file3"], stdout=f)
    
    Run Code Online (Sandbox Code Playgroud)

通常首选第二个,因为它避免了外壳的变化。

讨论区

当不使用外壳程序时,>只是命令行上的另一个字符。因此,请考虑错误消息:

paste: >: No such file or directory. 
Run Code Online (Sandbox Code Playgroud)

这表明paste已将其>作为参数接收,并正在尝试使用该名称打开文件。没有这样的文件。因此消息。

作为shell命令行,可以使用该名称创建文件:

touch '>'
Run Code Online (Sandbox Code Playgroud)

如果存在这样的文件paste,则当用调用subprocessshell=False,将使用该文件进行输入。