从python运行命令行并从内存中传递参数 [英] Running a command line from python and piping arguments from memory
问题描述
我想知道是否有一种方法可以在python中运行命令行可执行文件,但可以将内存中的参数值传递给它,而不必将内存数据写入磁盘上的临时文件中.从我看来,似乎subprocess.Popen(args)是从python脚本内部运行程序的首选方式.
I was wondering if there was a way to run a command line executable in python, but pass it the argument values from memory, without having to write the memory data into a temporary file on disk. From what I have seen, it seems to that the subprocess.Popen(args) is the preferred way to run programs from inside python scripts.
例如,我的内存中有一个pdf文件.我想使用大多数Linux发行版中提供的命令行函数pdftotext将其转换为文本.但是我不希望将内存中的pdf文件写到磁盘上的临时文件中.
For example, I have a pdf file in memory. I want to convert it to text using the commandline function pdftotext which is present in most linux distros. But I would prefer not to write the in-memory pdf file to a temporary file on disk.
pdfInMemory = myPdfReader.read()
convertedText = subprocess.<method>(['pdftotext', ??]) <- what is the value of ??
我应该调用什么方法,以及如何将内存数据传递到其第一个输入并将其输出传递回内存中的另一个变量?
what is the method I should call and how should I pipe in memory data into its first input and pipe its output back to another variable in memory?
我猜还有其他 pdf 模块可以在内存中进行转换,有关这些模块的信息会有所帮助.但是,为了将来参考,我也对如何从python内部将输入和输出传递到命令行感兴趣.
I am guessing there are other pdf modules that can do the conversion in memory and information about those modules would be helpful. But for future reference, I am also interested about how to pipe input and output to the commandline from inside python.
任何帮助将不胜感激.
推荐答案
> Popen.communicate :
with Popen.communicate:
import subprocess
out, err = subprocess.Popen(["pdftotext", "-", "-"], stdout=subprocess.PIPE).communicate(pdf_data)
这篇关于从python运行命令行并从内存中传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!