【问题标题】:pass arguments through a subprocess and terminate the subprocess when closing the main program in Python in Windows在 Windows 中关闭 Python 中的主程序时,通过子进程传递参数并终止子进程
【发布时间】:2019-08-10 04:06:16
【问题描述】:

我有两个 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的初学者。

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

【问题讨论】:

  • 考虑在单独的线程中运行
  • 能否详细说明?

标签: python windows error-handling subprocess parameter-passing


【解决方案1】:

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

但是将file2 作为模块导入file1 不是更容易吗? (如果对导入还不熟悉,可以参考this guide)

【讨论】:

  • 链接到另一个问题不是一个好的答案;不幸的是,这抵消了我对import 建议的+1。
猜你喜欢
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多