在 subprocess.call 中使用大于运算符
问题描述
我想做的很简单.我想使用 python 的 subprocess
模块调用以下命令.
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
该命令简单地工作并将file_A
的内容复制到当前工作目录中的file_B
.但是,当我尝试在脚本中使用 subprocess
模块调用此命令时,它会出错.以下是我正在做的事情:
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"])
我收到以下错误:
cat: /path/to/file_A: No such file or directory
cat: >: No such file or directory
cat: file_B: No such file or directory
我做错了什么?如何在子进程模块 call
命令中使用大于运算符?
what am I doing wrong ? How can I use the greater than operator with subprocess modules call
command ?
解决方案
>
输出重定向是 shell 功能,但是 subprocess.call()
带有 args
列表和 shell=False
(默认)不使用 shell.
>
output redirection is a shell feature, but subprocess.call()
with an args
list and shell=False
(the default) does not use a shell.
您必须在此处使用 shell=True
:
subprocess.call("cat /path/to/file_A > file_B", shell=True)
或者更好的是,使用 subprocess
将命令的输出重定向到文件:
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)
如果您只是复制文件,请使用 shutil.copyfile()
函数 让 Python 复制文件:
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')
相关文章