创建并通过管道将文件状对象作为命令的输入 [英] Create and pipe a file-like object as input for a command
问题描述
如果可能,我正在寻找一种更好的方法:
I'm looking for a better way to do this, if possible:
import subprocess
f = open('temp.file', 'w+')
f.write('hello world')
f.close()
out = subprocess.check_output(['cat', 'temp.file'])
print out
subprocess.check_output(['rm', 'temp.file'])
在此示例中,我正在创建一个文件并将其作为输入传递给 cat
(实际上,我正在运行的不是 cat
,而是一些其他程序来解析输入 pcap
文件).
In this example I'm creating a file and passing it as input to cat
(in reality it's not cat
I'm running but some other program that parses an input pcap
file).
我想知道的是,在Python中是否有一种方法可以创建带有某些内容的文件状对象",并将该文件状对象作为管道输入到命令行程序.如果可以的话,我认为这比将文件写入磁盘然后删除该文件更为有效.
What I'm wondering is, is there a way in Python I can create a 'file-like object' with some content, and pipe this file-like object as input to a command-line program. If it is possible, I reckon it would be more efficient than writing a file to the disk and then deleting that file.
推荐答案
check_output
使用 stdin
输入参数来指定类似于文件的对象以连接到流程的标准输入.
check_output
takes a stdin
input argument to specify a file-like object to connect to the process's standard input.
with open('temp.file') as input:
out = subprocess.check_output(['cat'], stdin=input)
此外,也无需花钱运行 rm
;您可以直接从Python删除文件:
Also, there's no need to shell out to run rm
; you can remove the file directly from Python:
os.remove('temp.file')
这篇关于创建并通过管道将文件状对象作为命令的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!