How to get program output in Python?

I am not a Perl user, but from this question I deduced that it is extremely easy to get the standard output of a program executed through a Perl script using something similar to:

$version = `java -version`;  

How do I get the same end result in Python? Does this line cause a standard error (equivalent to C ++ std :: cerr) and a standard log (std :: clog)? If not, how can I get these output streams?

Thanks Geoff

+3
source share
3 answers

For python 2.5: unfortunately not. You need to use a 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

+7
source

Python 2.7 +

from subprocess import check_output as qx

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

Python < 2.7.

+6

, Python subprocess.

- , ​​, :

#!/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)

... :

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

... - .

. shlex.split() shell=True

, . , , , , (, captcmd(...)[1] ). , , stdout stderr . "" Backtick Perl. ( shlex.split(), - , Perl).

+4

Source: https://habr.com/ru/post/1744803/


All Articles