在 git bash 下使用 subprocess.Popen 查看意外的同步行为

Seeing unexpected synchronous behavior using subprocess.Popen under git bash

我无权访问 Windows,但我为 co-worker 到 运行 编写了一些测试代码,它表明 subprocess.Popen 是同步运行的在 git bash 下,异步在 Windows CMD.

child 进程在终止前休眠了 5 秒,但是 parent 中 subprocess.Popen 之后的代码直到 child 之后才在 git bash 下执行=] 退出。 Python 3.7 和 3.10 都是如此。

我找不到任何文档表明这是预期的行为,而且在 macOS 或 Linux 下肯定不会这样。

Parent

#! /usr/bin/env python
import subprocess, time, sys
proc = subprocess.Popen(['python', 'child.py'])
print(f'Parent: launched child process {proc.pid}.')
time.sleep(10)
print('Parent: Done sleeping, terminating.')
sys.exit(0)

Child

#! /usr/bin/env python
import time, sys
print("Child: I'm going to sleep for 5 seconds.")
time.sleep(5)
print("Child: I'm awake again. Exiting.")
sys.exit(-1)

命令

Parent: launched child process 12244.
Child: I'm going to sleep for 5 seconds.
Child: I'm awake again. Exiting.
Parent: Done sleeping, terminating.

Git bash

Child: I'm going to sleep for 5 seconds.
Child: I'm awake again. Exiting.
Parent: launched child process 85372.
Parent: Done sleeping, terminating.

这是一个打印缓冲问题,您可以 运行 父级:

python -u parent.py