问题描述
我想做的很简单.我想使用 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')
这篇关于在 subprocess.call 中使用大于运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)