为什么 Eclipse 没有 运行 子进程?

Why does Eclipse not run the 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 环境有关。当我在终端上查看 sys.path 和 IDE 时,它们是相同的,除了 Eclipse IDE 还包括与我的 Eclipse 项目文件夹相关的路径。我已经看到其他 post 个关于 Eclipse 和子进程的问题 subprocess.Popen() has inconsistent behavior between Eclipse/PyCharm and terminal execution 但问题和答案并没有让我找到解决方案,但也许它会帮助其他有类似问题的人。

好的,我知道问题出在哪里了。问题根本不在于 Eclipse IDE,而是我对 subprocess.Popen 工作原理的误解。 subprocess.Popen class 不等待子进程完成。因此,由于函数 argums 正在调用进一步的子进程,因此 Popen class 没有等待这些子进程完成,因此脚本在顶层进程中停滞。如果我替换:

 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)

现在可以了。希望这对其他人有帮助。