How to redirect output with subprocess in Python?

后端 未结 5 1643
孤街浪徒
孤街浪徒 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:26

    In Python 3.5+ to redirect the output, just pass an open file handle for the stdout argument to subprocess.run:

    # Use a list of args instead of a string
    input_files = ['file1', 'file2', 'file3']
    my_cmd = ['cat'] + input_files
    with open('myfile', "w") as outfile:
        subprocess.run(my_cmd, stdout=outfile)
    

    As others have pointed out, the use of an external command like cat for this purpose is completely extraneous.

提交回复
热议问题