How to get the output from an external program and put it in a variable in Python
I'm still pretty new to the python world and know this should be a simple question to answer. I have this script section in python that calls a script in Perl. This Perl script is a SOAP service that retrieves data from a web page. Everything works fine and outputs what I want, but after a bit of trial and error, I am confused as to how I can grab the data using a python variable and not just output to the screen as it is now.
Any pointers appreciated!
Thank,
Pablo
# SOAP SERVICE
# Fetch the perl script that will request the users email.
# This service will return a name, email, and certificate.
var = "soap.pl"
pipe = subprocess.Popen(["perl", "./soap.pl", var], stdin = subprocess.PIPE)
pipe.stdin.write(var)
print "\n"
pipe.stdin.close()
source to share
I'm not sure what your code is supposed to do (with var
in particular), but here's the basics.
There is a subprocess.check_output () function for this
import subprocess
out = subprocess.check_output(['ls', '-l'])
print out
If your Python before 2.7 uses Popen with the link () method
import subprocess
proc = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
out, err = proc.communicate()
print out
You can iterate instead proc.stdout
, but it seems like you want all the output to be in one variable.
In both cases, you provide the program arguments in a list.
Or add stdin
as needed
proc = subprocess.Popen(['perl', 'script.pl', 'arg'],\
stdin = subprocess.PIPE,\
stdout = subprocess.PIPE)
The goal stdin = subprocess.PIPE
is to provide stdin
to start the process when it starts. Then you do proc.stdin.write(string)
and it will write to the called program stdin
. This program usually waits for its own, stdin
and after you send a newline, it will receive everything written on it (starting with the last line of the newline) and perform the appropriate processing.
If you just need to pass parameters / arguments to the script when you call it, then that is not needed at all and does not include it stdin
.
In Python 3 (since 3.5) the recommended method is subprocess.run ()
source to share