首页 > 解决方案 > 关闭脚本时,stderr 改变了 python 的 Popen 的行为

问题描述

我在 python2 上使用这个脚本来启动一个应用程序,然后立即退出 python 脚本而不等待子进程结束。这是我的代码:

kwargs = {}
if platform.system() == 'Windows':
    # from msdn [1]
    CREATE_NEW_PROCESS_GROUP = 0x00000200  # note: could get it from subprocess
    DETACHED_PROCESS = 0x00000008          # 0x8 | 0x200 == 0x208
    kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
    kwargs.update(stderr=subprocess.PIPE)
elif sys.version_info < (3, 2):  # assume posix
    kwargs.update(preexec_fn=os.setsid)
else:  # Python 3.2+ and Unix
    kwargs.update(start_new_session=True)

subprocess.Popen([APP], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,**kwargs)

它在 python 2.7 上工作正常,但它不会在没有更改的情况下在 python 3.7 上启动预期的“APP”。

为了让它在 python3 中工作,我找到了两个独立的解决方法:

  1. 将 stderr 更改为:stderr=subprocess.DEVNULL

或者

  1. 在Popen之后(关闭脚本之前)添加time.sleep(0.1)调用。

我认为这实际上与python无关,而是与在python脚本可以安全退出之前进程打开后需要发生的某些事件有关?

有什么提示吗?我真的很想知道为什么会这样。现在我只是添加了睡眠呼叫。

谢谢

标签: scriptingprocesspython-3.x

解决方案


推荐阅读