本文介绍了subprocess.Popen()在Eclipse/PyCharm和终端执行之间的行为不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是Eclipse/PyCharm与标准终端不同地解释子进程的Popen()结果.所有人都在OSX上使用python2.6.1.

The problem I'm having is with Eclipse/PyCharm interpreting the results of subprocess's Popen() differently from a standard terminal. All are using python2.6.1 on OSX.

这是一个简单的示例脚本:

Here's a simple example script:

import subprocess

args = ["/usr/bin/which", "git"]
print "Will execute %s" % " ".join(args)
try:
  p = subprocess.Popen(["/usr/bin/which", "git"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  # tuple of StdOut, StdErr is the responses, so ..
  ret = p.communicate()
  if ret[0] == '' and ret[1] <> '':
    msg = "cmd %s failed: %s" % (fullcmd, ret[1])
    if fail_on_error:
      raise NameError(msg)
except OSError, e:
  print >>sys.stderr, "Execution failed:", e

在标准终端上,该行:

ret = p.communicate()

给我:

(Pdb) print ret
('/usr/local/bin/git\n', '')

Eclipse和PyCharm给我一个空的元组:

Eclipse and PyCharm give me an empty tuple:

ret = {tuple} ('','')

更改shell =值也不能解决问题.在终端上,设置shell = True,然后完全传递命令(即args = ["/usr/bin/which git"]),得到的结果是相同的:ret =('/usr/local/bin/git \ n',"). Eclipse/PyCharm都给了我一个空的元组.

Changing the shell= value does not solve the problem either. On the terminal, setting shell=True, and passing the command in altogether (i.e., args=["/usr/bin/which git"]) gives me the same result: ret = ('/usr/local/bin/git\n', ''). And Eclipse/PyCharm both give me an empty tuple.

关于我可能做错了什么的任何想法?

Any ideas on what I could be doing wrong?

推荐答案

好,发现了问题,在Unix类型的环境中使用IDE时要牢记这一点很重要. IDE在与终端用户不同的环境上下文中运行(不是吗?!).我没有考虑到子进程使用的环境与终端环境所使用的环境不同(我的终端将bash_profile设置为在PATH中包含更多内容).

Ok, found the problem, and it's an important thing to keep in mind when using an IDE in a Unix-type environment. IDE's operate under a different environment context than the terminal user (duh, right?!). I was not considering that the subprocess was using a different environment than the context that I have for my terminal (my terminal has bash_profile set to have more things in PATH).

可以通过如下更改脚本来轻松验证这一点:

This is easily verified by changing the script as follows:

import subprocess
args = ["/usr/bin/which", "git"]
print "Current path is %s" % os.path.expandvars("$PATH")
try:
  p = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  # tuple of StdOut, StdErr is the responses, so ..
  out, err = p.communicate()
  if err:
    msg = "cmd %s failed: %s" % (fullcmd, err)
except OSError, e:
  print >>sys.stderr, "Execution failed:", e

在终端下,路径包括/usr/local/bin.在IDE下却没有!

Under the terminal, the path includes /usr/local/bin. Under the IDE it does not!

这对我来说是一个重要的陷阱-永远记住环境!

This is an important gotcha for me - always remember about environments!

这篇关于subprocess.Popen()在Eclipse/PyCharm和终端执行之间的行为不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 05:59