为什么Eclipse不运行子进程?

时间:2015-12-31 18:32:13

标签: python eclipse subprocess

真的很困惑,为什么这不起作用。我有一个python脚本,使用子进程模块运行另一个python脚本作为子进程:

##### outerscript.py

import subprocess

subprocess.Popen("python testpython.py --newscript 'this is the argument'", shell=True)

作为子进程运行的python脚本如下所示:

###### innerscript.py

import getopt

class Checkclass(object):

     def __init__(self):
         self.newscript = ''

     def check(self):
         print self.newscript 

     def complicatedcalculation(self):
         print 1+1


def argums(argv):
    checkclass = Checkclass()
    checkclass.check()
    checkclass.complicatedcalculation()

#Generates and interprets a list of options which can be passed as arguments to the class Checkclass
    try:
       opts, args = getopt.getopt(sys.argv[1:], "h", ["newscript="])
    except getopt.GetoptError, err:
       print str(err)
       checkclass.usage()
       sys.exit(2)
    output = None
    verbose = False


    for o, a in opts:

        if o in ("-h", "--help"):
            #usage function not shown for simplicity-sake
            checkclass.usage()
            sys.exit()
        elif o == "--newscript":
            if a in ("-h", "--help", "--livescript"):
                print "need to define --newscript"
                checkclass.usage()
                sys.exit()
            else:
                checkclass.newscript = a

     checkclass.check()

if __name__ == "__main__":
    argums(sys.argv[1:])

当我运行此脚本时,它会生成一个错误说明

追踪(最近一次通话):   文件" innerscript.py",第45行,

第45行涉及要执行的脚本的第一行,即

argums(sys.argv[1:])

这个错误似乎并不具备信息。我一直试图想出一个解决方案。我已经尝试通过子进程运行其他更简单的python脚本,它们似乎工作正常。我也可以在终端上运行这个确切的subprocess.Popen命令,没有任何问题,因此它表明它与Eclipse IDE环境有关。当我查看终端和IDE上的sys.path时,除了Eclipse IDE还包含与我的Eclipse项目文件夹相关的路径之外,它们是相同的。我见过其他人发布有关Eclipse和子进程问题的问题 subprocess.Popen() has inconsistent behavior between Eclipse/PyCharm and terminal execution但问题和答案并没有让我找到解决方案,但也许它会帮助其他类似问题的人。

1 个答案:

答案 0 :(得分:1)

好的我弄清楚问题是什么。问题根本不在于Eclipse IDE,而在于我对subprocess.Popen如何工作的误解。 subprocess.Popen类不等待子进程完成。因为函数argums正在调用更多的子进程,所以Popen类没有等待那些子进程完成,因此脚本在顶级进程停止。如果我更换:

 subprocess.Popen("python testpython.py --newscript 'this is the argument'", shell=True)

使用

 subprocess.Popen("python testpython.py --newscript 'this is the argument'", shell=True).wait()

 subprocess.call("python testpython.py --newscript 'this is the argument'", shell=True)

它现在有效。希望这对其他人有所帮助。