Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Popen - Advance Usage of subprocess¶
Capture and handle the output of a long running process.
import subprocess as sp
import shlex
import timedef run_command(cmd):
process = sp.Popen(shlex.split(cmd), stdout=sp.PIPE)
while True:
output = process.stdout.readline().decode()
if output == "" and process.poll() is not None:
break
if output:
print(output.strip())
print("----")
time.sleep(0.1)
rc = process.poll()
return rcprocess = sp.Popen("date; date; date; date;", shell=True, stdout=sp.PIPE)process.stdout.readline().decode()'Sat 24 Aug 2019 03:23:36 PM PDT\n'process.stdout.readline().decode()'Sat 24 Aug 2019 03:23:36 PM PDT\n'process.stdout.readline().decode()'Sat 24 Aug 2019 03:23:36 PM PDT\n'process.stdout.readline().decode()'Sat 24 Aug 2019 03:23:36 PM PDT\n'process.stdout.readline().decode()''process.poll()0https://
import subprocess
import shlex
import time
def run_command(cmd):
process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
while True:
output = process.stdout.readline().decode()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
print('----')
time.sleep(1)
rc = process.poll()
return rc## Terminate a Python subprocess launched with `shell=True`
https://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true
## References
https://docs.python.org/3/library/subprocess.html#subprocess.Popen
https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python
https://codecalamity.com/run-subprocess-run/
https://stackoverflow.com/questions/53209127/subprocess-unexpected-keyword-argument-capture-output