How do I retrieve program output in Python?

I'm not a Perl user, but from this question deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to:

$version = `java -version`;  

How would I go about getting the same end result in Python? Does the above line retrieve standard error (equivalent to C++ std::cerr) and standard log (std::clog) output as well? If not, how can I retrieve those output streams as well?

Thanks, Geoff


Asked by: Victoria175 | Posted: 30-11-2021






Answer 1

For python 2.5: sadly, no. You need to use subprocess:

import subprocess
proc = subprocess.Popen(['java', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()

Docs are at http://docs.python.org/library/subprocess.html

Answered by: Kelsey221 | Posted: 01-01-2022



Answer 2

In Python 2.7+

from subprocess import check_output as qx

output = qx(['java', '-version'])

The answer to Capturing system command output as a string question has implementation for Python < 2.7.

Answered by: Haris961 | Posted: 01-01-2022



Answer 3

As others have mentioned you want to use the Python subprocess module for this.

If you really want something that's more succinct you can create a function like:

#!/usr/bin/env python 
import subprocess, shlex

def captcmd(cmd):
    proc = subprocess.Popen(shlex.split(cmd), \
      stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)

    out, err = proc.communicate()
    ret = proc.returncode
    return (ret, out, err)

... then you can call that as:

ok, o, e = captcmd('ls -al /foo /bar ...')
print o
if not ok:
    print >> sys.stderr, "There was an error (%d):\n" % ok
    print >> sys.stderr, e

... or whatever.

Note: I'm using shlex.split() as a vastly safer alternative to shell=True

Naturally you could write this to suit your own tastes. Of course for every call you have to either provide three names into which it can unpack the result tuple or you'd have to pull the desired output from the result using normal indexing (captcmd(...)[1] for the output, for example). Naturally you could write a variation of this function to combine stdout and stderr and to discard the result code. Those "features" would make it more like the Perl backtick expressions. (Do that and take out the shlex.split() call and you have something that's as crude and unsafe as what Perl does, in fact).

Answered by: Haris254 | Posted: 01-01-2022



Similar questions

How to retrieve an output of a Python script using a Java program

I am having a problem with my code. I have a java class that calls a python script that get gps data. The problem is that I can call the script but I want to return the data to a string on the java side so I can use it in an array later. So basically all I want is to take the data from the python script and bring it to java as a string and place it in to an array. python code #...


How to retrieve an output of a Python script using a Java program

I am having a problem with my code. I have a java class that calls a python script that get gps data. The problem is that I can call the script but I want to return the data to a string on the java side so I can use it in an array later. So basically all I want is to take the data from the python script and bring it to java as a string and place it in to an array. python code #...


Retrieve stderr from a python program in a c++ one

I'm currently trying to launch a file written in python from my C++ program with the pstream library (http://pstreams.sourceforge.net/). My code look like this: QStringList res; QStringList resErrors; // run a process and create a streambuf that reads its stdout and stderr redi::pstream proc(cmd, redi::pstreams::pstdout | redi::pstrea...


html - How can I retrieve the page title of a webpage using Python?

How can I retrieve the page title of a webpage (title html tag) using Python?


python - How to retrieve an element from a set without removing it?

Suppose the following: &gt;&gt;&gt; s = set([1, 2, 3]) How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host. Quick and dirty: &gt;&gt;&gt; elem = s.pop() &gt;&gt;&gt; s.add(elem)


sql server - Python: Retrieve Image from MSSQL

I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image! The following is my code: #!/usr/bin/python import _mssql mssql=_mssql.connect('&lt;ServerIP&gt;','&lt;UserID&gt;','&lt;Password&gt;') mssql.select_db('&lt;Database...


python - Best way to retrieve variable values from a text file?

Referring on this question, I have a similar -but not the same- problem.. On my way, I'll have some text file, structured like: var_a: 'home' var_b: 'car' var_c: 15.5 And I need that python read the file and then create a variable named var_a with value 'home', and so on. Example...


python - How to retrieve the selected text from the active window

I am trying to create a simple open source utility for windows using Python that can perform user-defined actions on the selected text of the currently active window. The utility should be activated using a pre-defined keyboard shortcut. Usage is partially outlined in the following example: The user selects some text using the mouse or the keyboard (in any application window)


python - How can I retrieve last x elements in Django

I am trying to retrieve the latest 5 posts (by post time) In the views.py, if I try blog_post_list = blogPosts.objects.all()[:5] It retreives the first 5 elements of the blogPosts objects, how can I reverse this to retreive the latest ones? Cheers


python - Retrieve module object from stack frame

Given a frame object, I need to get the corresponding module object. In other words, implement callers_module so this works: import sys from some_other_module import callers_module assert sys.modules[__name__] is callers_module() (That would be equivalent because I can generate a stack trace in the function for this test case. The imports are there simply to make that example complete an...


How do I retrieve Hotmail contacts with python

How can I retrieve contacts from hotmail with python? Is there any example?


linux - How to retrieve the process start time (or uptime) in python

How to retrieve the process start time (or uptime) in python in Linux? I only know, I can call "ps -p my_process_id -f" and then parse the output. But it is not cool.


python - Retrieve the two highest item from a list containing 100,000 integers

How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top