Given the following code example:
# save as test.py
import subprocess as sp
import time
script = '''#!/bin/bash
nohup sleep 10 &
'''
with open('test.sh', 'w') as f:
f.write(script)
start_ts = time.time()
cp = sp.run('bash test.sh', shell=True, capture_output=True)
print(f'Elapsed time: {time.time() - start_ts:.2f}s')
When running the above code with python test.py,
what I expect is it should stop immediately,
but instead it is pending for 10s.
Why is that? How can I fix it?
capture_output=Falseorsleep 10 >/dev/null 2>&1 &.shell=Trueis rarely the right thing to do, though sometimes, such as here, it doesn't actually break anything. That causes Python to run the specified command via a shell, instead of directly. You need it if the command you give uses shell-specific syntax, such as piping or heredocs or other redirections. Otherwise, it's needless and occasionally problematic.