Ben Chuanlong Du's Blog

It is never too late to learn.

Popen - Advanced Usage of subprocess

Popen - Advance Usage of subprocess

Capture and handle the output of a long running process.

In [3]:
import subprocess as sp
import shlex
import time
In [4]:
def 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 rc
In [8]:
process = sp.Popen("date; date; date; date;", shell=True, stdout=sp.PIPE)
In [9]:
process.stdout.readline().decode()
Out[9]:
'Sat 24 Aug 2019 03:23:36 PM PDT\n'
In [10]:
process.stdout.readline().decode()
Out[10]:
'Sat 24 Aug 2019 03:23:36 PM PDT\n'
In [11]:
process.stdout.readline().decode()
Out[11]:
'Sat 24 Aug 2019 03:23:36 PM PDT\n'
In [12]:
process.stdout.readline().decode()
Out[12]:
'Sat 24 Aug 2019 03:23:36 PM PDT\n'
In [13]:
process.stdout.readline().decode()
Out[13]:
''
In [14]:
process.poll()
Out[14]:
0

https://www.endpoint.com/blog/2015/01/28/getting-realtime-output-using-python

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
In [ ]:
## 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
In [ ]:
 

Comments