Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (19.9k points)

There are some commands in Linux with "fancy" output - by "fancy" I mean that it is colourful and it is real-time ie it overwrites itself, the best example is the output of the top command, another example could be docker build (it refreshes times (0.5s in the example below) interactively during build, see the demo):

[+] Building 0.5s (3/3) FINISHED                                                                                                                                

 => [internal] load .dockerignore                                0.0s

 => => transferring context: 2B                                  0.0s

 => [internal] load build definition from Dockerfile             0.0s

 => => transferring dockerfile: 518B                             0.0s

 => ERROR resolve image config for ...                           0.5s


My question, is how can I have the same output while running a process in Python (presumably with subprocess.Popen)? I am primarily interested in Linux.

PS The closest I could achieve was colourful output via allocating tty:

out_r, out_w = pty.openpty()

p = subprocess.Popen(command, stdout=out_w, stderr=subprocess.STDOUT, shell=True)


while True:


      output =, 1000).decode()


But it, unsurprisingly, prints everything below, without rewriting content.

1 Answer

0 votes
by (25.1k points)

You can use the pexepect.spawn methods for this task.

import pexpect

child = pexpect.spawn(<command_line_str>)


Related questions

0 votes
1 answer
+1 vote
1 answer
0 votes
1 answer
asked Oct 8, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories