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

问题描述 投票:84回答:5

我在命令行中做了什么:

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
python subprocess
5个回答
20
投票

更新:不鼓励使用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)

234
投票

要回答您的原始问题,要重定向输出,只需将stdout参数的打开文件句柄传递给subprocess.call

# 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.call(my_cmd, stdout=outfile)

但正如其他人所指出的那样,为此目的使用像cat这样的外部命令是完全无关紧要的。


4
投票

@PoltoS我想加入一些文件,然后处理生成的文件。我认为使用猫是最简单的选择。有更好的/ pythonic方式吗?

当然:

with open('myfile', 'w') as outfile:
    for infilename in ['file1', 'file2', 'file3']:
        with open(infilename) as infile:
            outfile.write(infile.read())

0
投票

一个有趣的案例是通过向其添加类似文件来更新文件。然后,不必在此过程中创建新文件。在需要附加大文件的情况下,它特别有用。这是直接从python使用teminal命令行的一种可能性。

import subprocess32 as sub

with open("A.csv","a") as f:
    f.flush()
    sub.Popen(["cat","temp.csv"],stdout=f)

0
投票
size = 'ffprobe -v error -show_entries format=size -of default=noprint_wrappers=1:nokey=1 dump.mp4 > file'
proc = subprocess.Popen(shlex.split(size), shell=True)
time.sleep(1)
proc.terminate() #proc.kill() modify it by a suggestion
size = ""
with open('file', 'r') as infile:
    for line in infile.readlines():
        size += line.strip()

print(size)
os.remove('file')

当你使用子进程时,必须杀死进程。这是一个例子。如果你没有杀死进程,文件将是空的,你什么都不读。它可以在Windows上运行。我不能确保它可以在Unix上运行。

© www.soinside.com 2019 - 2024. All rights reserved.