如何在Python中使用子进程重定向输出?
我在命令行中做什么:
cat file1 file2 file3 > myfile
我想用 python 做什么:
import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program
What I do in the command line:
cat file1 file2 file3 > myfile
What I want to do with python:
import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 Python 3.5+ 中,要重定向输出,只需将
stdout
参数的打开文件句柄传递给subprocess.run
:正如其他人指出的那样,为此目的使用像
cat
这样的外部命令是完全无关的。In Python 3.5+ to redirect the output, just pass an open file handle for the
stdout
argument tosubprocess.run
:As others have pointed out, the use of an external command like
cat
for this purpose is completely extraneous.更新:不鼓励使用 os.system,尽管它在 Python 3 中仍然可用。
使用 os.system:
如果你真的想使用子进程,这里是解决方案(主要来自子进程的文档):
OTOH,您可以完全避免系统调用:
UPDATE: os.system is discouraged, albeit still available in Python 3.
Use
os.system
:If you really want to use subprocess, here's the solution (mostly lifted from the documentation for subprocess):
OTOH, you can avoid system calls entirely:
当然:
Of course:
当你使用 subprocess 时,必须杀死该进程。这是一个例子。如果你不杀死该进程,file 将是空的,你什么也读不到。可以在Windows上运行。我无法确保它可以在Unix上运行。
When you use subprocess , the process must be killed.This is an example.If you don't kill the process , file will be empty and you can read nothing.It can run on Windows.I can`t make sure that it can run on Unix.
如果您的
args
看起来像['sh', '-c', 'cat file1 file2 file3 > ,它将起作用。 myfile']
这将意味着cat
的输出不会传递 Python 并在 shell 中生成(插入sh -c
你可以使用bash-c
)It will work if your
args
will look like['sh', '-c', 'cat file1 file2 file3 > myfile']
it will mean that output ofcat
won't pass Python and spawn in shell instead (insted ofsh -c
you can usebash -c
)一个有趣的情况是通过向文件附加类似的文件来更新文件。这样就不必在此过程中创建新文件。它在需要附加大文件的情况下特别有用。这是直接从 python 使用终端命令行的一种可能性。
One interesting case would be to update a file by appending similar file to it. Then one would not have to create a new file in the process. It is particularly useful in the case where a large file need to be appended. Here is one possibility using teminal command line directly from python.