【问题标题】:Do NOT terminate python subprocess when script ends脚本结束时不要终止 python 子进程
【发布时间】:2014-09-27 10:49:29
【问题描述】:

我已经看到了很多与此相反的问题,我觉得这很奇怪,因为我无法阻止我的子进程关闭,但有没有办法调用 subprocess.Popen 并确保调用python脚本退出后它的进程保持运行?

我的代码如下:

dname = os.path.dirname(os.path.abspath(__file__))
script = '{}/visualizerUI.py'.format(dname)
self.proc = subprocess.Popen(['python', script, str(width), str(height), str(pixelSize)], stdout=subprocess.PIPE)

这可以很好地打开进程,但是当我关闭脚本时(因为它完成或使用 Ctrl+C),它也会关闭 VisualizerUI.py 子进程,但我希望它保持打开状态。或者至少可以选择。

我错过了什么?

【问题讨论】:

  • this answer 适合你吗?
  • 您是否尝试过将脚本分叉到后台?
  • 嗯??不要认为 Windows 有分叉

标签: python subprocess


【解决方案1】:

另一种选择是使用:

import os
os.system("start python %s %s %s %s" % (script, str(width), str(height), str(pixelSize)))

使用新控制台在新进程中启动新的 Python 脚本。

编辑:刚刚看到您正在使用 Mac,所以我怀疑这是否适合您。

怎么样:

import os
import platform

operating_system = platform.system().lower()
if "windows" in operating_system:
    exe_string = "start python"
elif "darwin" in operating_system:
    exe_string = "open python"
else:
    exe_string = "python"
os.system("%s %s %s %s %s" % (exe_string, script, str(width),
          str(height), str(pixelSize))))

【讨论】:

  • 我的目标是 Mac、Windows 和 Linux...所以它需要在任何地方都可以工作。
  • 显然在 Mac 上,等效命令是“打开”,但我附近没有要测试的命令。
【解决方案2】:

删除 stdout=subprocess.PIPE 并添加 shell=True 以便它在可分离的子shell 中生成。

【讨论】:

  • 如果我添加 shell=True 它在 Mac 上不起作用。如果没有标准输出部分,它也会做同样的事情。
  • By doesn't work on Mac 我的意思是窗口没有出现(visualizerUI.py 运行 Tkinter 应用程序)
  • 使用 shell=True 时仍然做同样的事情
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 2014-10-25
  • 1970-01-01
相关资源
最近更新 更多