[英]Using greater than operator with subprocess.call
What I am trying to do is pretty simple. 我想做的很简单。 I want to call the following command using python's subprocess
module. 我想使用python的subprocess
模块调用以下命令。
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. 该命令只是工作,并将file_A
的内容file_A
到当前工作目录中的file_B
。 However when I try to call this command using the subprocess
module in a script it errors out. 但是,当我尝试在脚本中使用subprocess
模块调用此命令时,它会出错。 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 ? 如何在子进程模块call
命令中使用大于运算符?
>
output redirection is a shell feature, but subprocess.call()
with an args
list and shell=False
(the default) does not use a shell. >
输出重定向为一个壳的特性,但是subprocess.call()
与args
列表和shell=False
(缺省值)不使用的壳。
You'll have to use shell=True
here: 你必须在这里使用shell=True
:
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: 或者更好的是,使用subprocess
将命令的输出重定向到文件:
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: 如果您只是复制文件,请使用shutil.copyfile()
函数让Python复制文件:
import shutil
shutil.copyfile('/path/to/file_A', 'file_B')
Addition to Martijn's answer: 除了Martijn的回答:
you can do the same thing as cat
yourself: 你可以cat
自己做同样的事情:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.