Home > database >  Seeing unexpected synchronous behavior using subprocess.Popen under git bash
Seeing unexpected synchronous behavior using subprocess.Popen under git bash

Time:04-19

I don't have access to Windows, but I wrote some test code for a co-worker to run, and it demonstrated that subprocess.Popen was behaving synchronously under git bash, asynchronously under Windows CMD.

The child process sleeps for 5 seconds before terminating, yet the code following subprocess.Popen in the parent does not execute under git bash until after the child exits. This was true using both Python 3.7 and 3.10.

I can't find any documentation to indicate that this is expected behavior, and it certainly doesn't behave that way under macOS or 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)

CMD

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.

CodePudding user response:

It's a print buffering issue, you can run the parent with:

python -u parent.py
  • Related