Python – How to take output from an external program and put it into a variable in Python

How to take output from an external program and put it into a variable in Python… here is a solution to the problem.

How to take output from an external program and put it into a variable in Python

I’m new to the Python world, and I know this should be an easy question to answer. I have a script in python that calls a script in Perl. This Perl script is a SOAP service that gets data from a Web page. Everything was fine, the output was what I wanted, but after trial and error, I was confused about how to capture data using python variables, not just output to the screen like now.

Thanks for any pointers!

Thanks,

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()

Solution

I’m not sure what the purpose of your code is (especially var), but it’s the basics.

There is subprocess.check_output().

import subprocess
out = subprocess.check_output(['ls', '-l'])
print out

If your Python is a version prior to 2.7, use Popen communicate() method

import subprocess
proc = subprocess. Popen(['ls', '-l'], stdout=subprocess. PIPE)
out, err = proc.communicate()
print out

You can iterate over proc.stdout instead, but you seem to want all outputs in one variable.

In both cases, you are in the list of provider parameters.

Or add stdin as needed

proc = subprocess. Popen(['perl', 'script.pl', 'arg'],\
    stdin  = subprocess. PIPE,\
    stdout = subprocess. PIPE)

stdin = subprocess. The purpose of PIPE is to be able to provide STDIN at runtime to start the process. Then you will execute proc.stdin.write(string) and write it to the calling program’s STDIN. The program usually waits on its STDIN, and after you send a newline, it writes everything to it (since the last newline) and runs the related processing.

If you only need to pass parameters/arguments to the script when the script is invoked, then its STDIN is usually not needed or involved.

Starting with Python 3.5, the recommended approach is subprocess.run(), which has an AND very similar full signature and similar operation constructor of Popen.

Related Problems and Solutions