0

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?

3
  • 2
    sleep inherits bash's stdout (nohup doesn't redirect it since it's not connected to a terminal) and keeps the subprocess pipe alive. Try capture_output=False or sleep 10 >/dev/null 2>&1 &. Commented Dec 26, 2024 at 5:25
  • 1
    @oguzismail redirect stdio do solve the problem. Commented Dec 26, 2024 at 5:31
  • shell=True is 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. Commented Dec 27, 2024 at 3:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.