Unexpected output using subprocess in Python

Posted by Vic on Stack Overflow See other posts from Stack Overflow or by Vic
Published on 2013-06-24T21:49:26Z Indexed on 2013/06/24 22:21 UTC
Read the original article Hit count: 180

Filed under:
|
|

I am trying to run a shell command from within my Python (version 2.6.5) code, but it is generating different output than the same command run within the shell (bash):

bash:

~> ifconfig eth0 | sed -rn 's/inet addr:(([0-9]{1,3}\.){3}[0-9]{1,3}).*/\1/p' | sed   's/^[ \t]*//;s/[ \t]*$//'
192.168.1.10

Python:

>>> def get_ip():
...     cmd_string = "ifconfig eth0 | sed -rn \'s/inet addr:(([0-9]{1,3}\.){3}[0-9]{1,3}).*/\1/p' | sed 's/^[ \t]*//;s/[ \t]*$//\'"
...     process = subprocess.Popen(cmd_string, shell=True, stdout=subprocess.PIPE)
...     out, err = process.communicate()
...     return out
... 
>>> get_ip()
'\x01\n'

My guess is that I need to escape the quotes somehow when running in python, but I am not sure how to go about this.

NOTE: I cannot install additional modules or update python on the machine that this code needs to be run on. It needs to work as-is with Python 2.6.5 and the standard library.

© Stack Overflow or respective owner

Related posts about python

Related posts about bash