简体   繁体   English

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

[英]How to redirect output with subprocess in Python?

What I do in the command line:我在命令行中执行的操作:

cat file1 file2 file3 > myfile

In Python 3.5+ to redirect the output, just pass an open file handle for the stdout argument to subprocess.run :Python 3.5+中重定向输出,只需将stdout参数的打开文件句柄传递给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.正如其他人指出的那样,为此目的使用像cat这样的外部命令是完全无关紧要的。

UPDATE: os.system is discouraged, albeit still available in Python 3.更新:不鼓励使用 os.system,尽管在 Python 3 中仍然可用。


Use os.system :使用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: OTOH,您可以完全避免系统调用:

import shutil

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

@PoltoS I want to join some files and then process the resulting file. @PoltoS 我想加入一些文件,然后处理生成的文件。 I thought using cat was the easiest alternative.我认为使用 cat 是最简单的选择。 Is there a better/pythonic way to do it?有没有更好的/pythonic方法来做到这一点?

Of course:当然:

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

One interesting case would be to update a file by appending similar file to it.一个有趣的案例是通过向文件附加类似文件来更新文件。 Then one would not have to create a new file in the process.这样就不必在此过程中创建新文件了。 It is particularly useful in the case where a large file need to be appended.它在需要附加大文件的情况下特别有用。 Here is one possibility using teminal command line directly from python.这是直接从 python 使用终端命令行的一种可能性。

import subprocess32 as sub

with open("A.csv","a") as f:
    f.flush()
    sub.Popen(["cat","temp.csv"],stdout=f)
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')

When you use subprocess , the process must be killed.This is an example.If you don't kill the process , file will be empty and you can read nothing.It can run on Windows .I can`t make sure that it can run on Unix.当你使用进程时,进程必须被杀死。这是一个例子。如果你不杀死进程,文件将是空的,你什么也读不到。它可以在Windows上运行。我不能确保它可以在 Unix 上运行。

如果您的args<\/code>看起来像['sh', '-c', 'cat file1 file2 file3 > myfile']<\/code>它将起作用,这意味着cat<\/code>的输出不会通过 Python 而是在 shell 中生成(插入sh -c<\/code>你可以使用bash -c<\/code> )

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM