How to redirect output with subprocess in Python?

后端 未结 5 1555
孤街浪徒
孤街浪徒 2020-11-22 07:41

What I do in the command line:

cat file1 file2 file3 > myfile

What I want to do with python:

import subprocess, shlex
my         


        
5条回答
  •  醉话见心
    2020-11-22 08:09

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


    Use 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, 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)
    

提交回复
热议问题