brain storm brain storm - 19 days ago 7
Python Question

python: error when executing subprocess.popen

when I execute the following function in centos, I get error

def install_requests_lib():
try:
import requests
return
except ImportError, e:
print "module does not exist, installing..."
if(platform.system().lower()=='darwin'):
print "install requests before proceeding, run **sudo pip install requests**"
sys.exit(2)
elif(platform.system().lower()=='linux'):
print "installing"
p=Popen(["yum","-y","install","python-requests"], stdout=PIPE, shell=True)
p.communicate()
print p.returncode


error:

module does not exist, installing...
installing
You need to give some command
1


I cannot figure out why it is wrong.

I executed with
stdin=PIPE
argument, still i get same error.

Answer

The arguments in your arg list after "yum" aren't being executed if you give the argument shell=True. Remove the shell=True argument and it should work.

Alternatively, you could supply the full command line as a string and keep the shell=True argument:

p=Popen("yum install -y python-requests", stdout=PIPE, shell=True)

but it's generally discouraged to do so, for many reasons.