Using greater than operator with subprocess.call

柔情痞子 提交于 2019-11-26 17:13:11

问题


What I am trying to do is pretty simple. I want to call the following command using python's subprocess module.

cat /path/to/file_A > file_B

The command simply works and copies the contents of file_A to file_B in current working directory. However when I try to call this command using the subprocess module in a script it errors out. Following is what I am doing:

import subprocess

subprocess.call(["cat", "/path/to/file_A", ">", "file_B"])

and I get the following error:

cat: /path/to/file_A: No such file or directory
cat: >: No such file or directory
cat: file_B: No such file or directory

what am I doing wrong ? How can I use the greater than operator with subprocess modules call command ?


回答1:


> output redirection is a shell feature, but subprocess.call() with an args list and shell=False (the default) does not use a shell.

You'll have to use shell=True here:

subprocess.call("cat /path/to/file_A > file_B", shell=True)

or better still, use subprocess to redirect the output of a command to a file:

with open('file_B', 'w') as outfile:
    subprocess.call(["cat", "/path/to/file_A"], stdout=outfile)

If you are simply copying a file, use the shutil.copyfile() function to have Python copy the file across:

import shutil

shutil.copyfile('/path/to/file_A', 'file_B')



回答2:


Addition to Martijn's answer:

you can do the same thing as cat yourself:

with open("/path/to/file_A") as file_A:
    a_content = file_A.read()
with open("file_B", "w") as file_B:
    file_B.write(a_content)


来源:https://stackoverflow.com/questions/21135694/using-greater-than-operator-with-subprocess-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!