Python subprocess.Popen()在Eclipse/PyCharm和终端执行之间具有不一致的行为
我遇到的问题是Eclipse/PyCharm对子流程的Popen()结果的解释与标准终端不同。所有人都在OSX上使用python2.6.1 下面是一个简单的脚本示例:Python subprocess.Popen()在Eclipse/PyCharm和终端执行之间具有不一致的行为,python,eclipse,subprocess,popen,pycharm,Python,Eclipse,Subprocess,Popen,Pycharm,我遇到的问题是Eclipse/PyCharm对子流程的Popen()结果的解释与标准终端不同。所有人都在OSX上使用python2.6.1 下面是一个简单的脚本示例: import subprocess args = ["/usr/bin/which", "git"] print "Will execute %s" % " ".join(args) try: p = subprocess.Popen(["/usr/bin/which", "git"], shell=False, stdou
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
给我:
(Pdb) print ret
('/usr/local/bin/git\n', '')
Eclipse和PyCharm给了我一个空元组:
ret = {tuple} ('','')
更改shell=值也不能解决问题。在终端上,设置shell=True,并将命令全部传入(即args=[“/usr/bin/which git”])得到相同的结果:ret=(“/usr/local/bin/git\n”“,”)。Eclipse/PyCharm都给了我一个空元组
你知道我可能做错了什么吗?好的,找到了问题所在,在Unix类型的环境中使用IDE时要记住这一点。IDE是在不同于终端用户的环境环境下运行的(没错?!)。我没有考虑到子流程使用的环境与我的终端的上下文不同(我的终端将bash_配置文件设置为在路径中有更多内容) 通过如下更改脚本,可以轻松验证这一点:
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下它不会
这对我来说是一个重要的难题——永远记住环境 哇,我在窗户下也遇到了同样的问题,你给我指出了正确的方向!谢谢从控制台启动的解释器可以访问“系统”和“当前用户”$PATH变量,而从IDE或资源管理器启动的解释器或程序只能访问“系统”$PATH。让Eclipse包含终端提供的所有上下文的解决方案是什么?谢谢
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