I'm a Java & C programmer who is learning Python. I'm writing a Python program which needs to issue Linux commands and then capture the output. (Output should be a single line which python can store in a string... I hope.) I am on an older machine, running Python 2.4.3, and as far as I can see, the check_output call should do what I need.
Trouble is, python doesn't recognize check_output. Here's my prototype code:
#!/usr/bin/python
import sys
print "Current Python Version:: ", (sys.version)
import subprocess
from subprocess import check_output # <<<<<<<< error here!
output = subprocess.check_output(['ls', '-1', '|', 'grep', 'somefile.txt'])
print 'Have %d bytes in output' % len(output)
print output
Output is:
[Linux]$ python myCode.py
Current Python Version:: 2.4.3 (#1, Apr 14 2011, 20:41:59)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)]
Traceback (most recent call last):
File "myCode.py", line 7, in ?
from subprocess import check_output
ImportError: cannot import name check_output
[Linux]$
I'm using the below website as a doc guide; in fact, the last three lines of my code are more-or-less directly copied from this site's example:
https://pymotw.com/2/subprocess/#capturing-output
The doc says check_output is valid in Python 2.4 and up, so I should be okay. And yet my Python interpreter doesn't understand check_output.
So... what to make of this? It looks like my version is okay and Python can access subprocess but not check_output. Do I need to ask the admin to install a library or something? Or am I not importing the call correctly?
Also: I'm sort of assuming that check_output is the call I want here to capture a one-line output from my Linux command. Does that seem okay?
Thanks!