如何在Python中使用子进程重定向输出?

发布于 2021-02-02 23:17:49

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

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
关注者
0
被浏览
120
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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

    用途os.system:

    os.system(my_cmd)
    

    如果你确实要使用子流程,请使用以下解决方案(大部分内容来自子流程的文档):

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

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

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看