python: 执行时出错subprocess.popen

python: error when executing subprocess.popen

当我在centos中执行以下函数时,出现错误

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

错误:

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

我不知道哪里出了问题。

我使用 stdin=PIPE 参数执行,但我仍然得到同样的错误。

您正在尝试执行 yum -y install,而您的意思是 yum install -y

如果您给出参数 shell=True,您的参数列表中 "yum" 之后的参数将不会被执行。删除 shell=True 参数,它应该可以工作。

或者,您可以提供完整的命令行作为字符串并保留 shell=True 参数:

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

但通常不鼓励这样做,for many reasons