首页 > 解决方案 > 在 Windows 中关闭 Python 中的主程序时,通过子进程传递参数并终止子进程

问题描述

我有两个 Python 文件,文件 1 和文件 2,它们做两个不同的事情。我想一起运行它们。我正在使用 VS2017

文件 1 的伪代码是:

Class A:
   foo1():
    .
    .
   foo2();
    if variable<30;
        #do this
    else;
      process = subprocess.Popen('py file2.py' ,shell=True,stdin=None, stdout=None, stderr=None, close_fds=True)

    #rest of the code for foo2()

if __name__ == "__main__":   
  A.foo2();

我还想将变量传递给第二个文件。我正在研究类似的东西

variable = input("enter variable)
cmd = ['py file2.py', variable]
subprocess.Popen(cmd ,shell=True,stdin=None, stdout=None, stderr=None, close_fds=True)

我收到一条错误消息:

'"py subproleap.py"' 不是内部或外部命令、可运行程序或批处理文件。

即使我确实传递了变量,我如何让 file2.py 读取它?

任何帮助,将不胜感激。我是python的初学者。

EDIT1:为什么我使用子进程是我希望file2.py在后台运行,一旦满足条件,而主进程在旁边运行。

标签: pythonwindowserror-handlingsubprocessparameter-passing

解决方案


可能会回答您的问题(您正在使用shell=True参数)

file2但是作为一个模块导入不是更容易file1吗?(如果您还不熟悉导入,可以参考本指南


推荐阅读