Using greater than operator with subprocess.call(在 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')
这篇关于在 subprocess.call 中使用大于运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 subprocess.call 中使用大于运算符
基础教程推荐
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
