如何在 Python 中使用子进程重定向输出? [英] How to redirect output with subprocess in Python?

查看:41
本文介绍了如何在 Python 中使用子进程重定向输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在命令行中执行的操作:

What I do in the command line:

cat file1 file2 file3 > myfile

我想用python做什么:

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

推荐答案

更新:不鼓励使用 os.system,尽管在 Python 3 中仍然可用.

UPDATE: os.system is discouraged, albeit still available in Python 3.

使用os.system:

os.system(my_cmd)

如果您真的想使用子流程,这里是解决方案(主要来自子流程的文档):

If you really want to use subprocess, here's the solution (mostly lifted from the documentation for subprocess):

p = subprocess.Popen(my_cmd, shell=True)
os.waitpid(p.pid, 0)

OTOH,你可以完全避免系统调用:

OTOH, you can avoid system calls entirely:

import shutil

with open('myfile', 'w') as outfile:
    for infile in ('file1', 'file2', 'file3'):
        shutil.copyfileobj(open(infile), outfile)

这篇关于如何在 Python 中使用子进程重定向输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆