Skip to content Skip to sidebar Skip to footer

Running A Command Line From Python And Piping Arguments From Memory

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

Solution 1:

with Popen.communicate:

import subprocess
out, err = subprocess.Popen(["pdftotext", "-", "-"], stdout=subprocess.PIPE).communicate(pdf_data)

Solution 2:

os.tmpfile is useful if you need a seekable thing. It uses a file, but it's nearly as simple as a pipe approach, no need for cleanup.

tf=os.tmpfile()
tf.write(...)
tf.seek(0)
subprocess.Popen(  ...    , stdin = tf)

This may not work on Posix-impaired OS 'Windows'.

Solution 3:

Popen.communicate from subprocess takes an input parameter that is used to send data to stdin, you can use that to input your data. You also get the output of your program from communicate, so you don't have to write it into a file.

The documentation for communicate explicitly warns that everything is buffered in memory, which seems to be exactly what you want to achieve.

Post a Comment for "Running A Command Line From Python And Piping Arguments From Memory"