iam a newbie to python, i am trying to execute a shell command within python code and need the output of the shell command to be passed to the same python code for subsequent use. Here i need the value of the string "ListenPort" from the text file /tmp/file.txt to be stored in a variable. i will use that variable in the same pythin code.

cat /tmp/file.txt



here is the python code
import sys
import os
import subprocess

nm=subprocess.check_output("cat /tmp/file.txt | grep ListenPort | awk -F= '{print $2}'", shell=True)
print nm

File "/local/mnt/apps/ora/product/Middleware/user_projects/domains/bifoundation_domain/test1.py", line 4, in ?
ImportError: no module named subprocess\

/usr/bin/python -- output

Python 2.4.3 (#1, Jun 11 2009, 14:09:37)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2

Could some body please help me with this code, I am not sure why it says no module subprocess. If there is any other way to do the same thing i am fine with that as well.

i tried doing this as well

cmd_str1="nm=cat /tmp/file.txt | grep ListenPort | awk -F" + "=" + " '{print $2}'"
print nm

this throws Name Error nm.

where cat /tmp/file.txt gives me this output

how can I the output from a shell command be assigned as a value to a variable in python.

I kindly request somebody to help me with this piece of code.


Use this snippet and write

com = Command("cat /tmp/file.txt | grep ListenPort | awk -F").run()
if com.failed:
    print com.error
    print com.output

(correct the end of th awk command if necessary)

Thanks a lot Grib, I added the Command Class to my script. However I get this error Lexical error Encountered: "@" (64), after :""
Could you please let me know what could be wrong?
Thanks a ton again

Python 2.4 is very old, upgrade to 2.7. A good part of today's code doesn't run before 2.6. If you don't want to change your os' python, you can install more than one version of python at the same time.

Thanks a lot Grib, we dont control the python distributions on our servers, however i will install the newer version of python on the same box and try that.
thanks a lot for your help, really appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.