Python 3 showing progressbar while subprocess.Popen

Have an interesting case I want to share and save for future.

One small problem in this system: is showing when some process is running and was not hanged up.

Sometimes we need to run a huge amount of checks and tests and would be great to know if something hangs before killing it mannually.
I used different scenarios and mostly a module pregressbar2, and this is what I finally can compose:

  1. Make worker which will execute job sorf of randomly:
    1. import time
      import random
      print("START SOMETHING")
      for i in range(5):
          sec = random.randint(1, 3)
          print("Sleeping for: %d" % sec)
          print("Making job, line: %d" % i)
      print("END SOMETHING")
  2. Make process executor:
    1. import sys
      import subprocess
      import progressbar
      # Draw spinner:
      bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
      # Execute some job with multiple lines on stdout:
      p = subprocess.Popen("C:\Python34\python.exe", shell=True, stdout=subprocess.PIPE,
      # Lines will be collected in list:
      result = []
      # Until I get last line and the end of string:
      while p.stdout is not None:
          # Update spinner on one step:
          # It will update only when any line was printed to stdout!
          # Read each line:
          line = p.stdout.readline()
          # Add line in list and remove carriage return
          # When no lines appears:
          if not line:
      # Show finish message, it also useful because bar cannot start new line on console, why?
      # Results as string:


Voilla! But there is still a small problem – this bar will update it’s state only when process post something in stdout. Between posts it will stay calm for random amount of time (as designed in worker). If I’ll update while or somehow try to make this loop faster – it becomes a deadlock. 


Next example is from:

Function: tests_executor.

In this example – bar works better, because It have a list of tests, so I can enumerate its len and config bar to show how much progress were already done.

But yes, it will update only each one itetarion, and till test run, for 600+ sec – it wouldn’t move.

    def tests_executor(self, tests_list):

        tests_len = len(tests_list)

        if progressbar:
            bar = progressbar.ProgressBar(max_value=tests_len)
            log.debug("Module progressbar2 is not installed, will show progress in usual manner.")
            pass"-==== START RELATED TESTS EXECUTION ====-")
        log.debug("Tests related to: "+str(tests_list[0]['pattern']))
        log.debug("All tests len: "+str(tests_len))

        for i, test in enumerate(tests_list):

  "Start test:" + str(test['rem_test_path']))

            if progressbar:

  "%d test of "+str(tests_len), i+1)  # Just print

            pre_cmd = ". ~/.bash_profile;"
            wd_cmd = "cd "+test['rem_test_wd']+";"
            cmd_test = "/usr/tideway/bin/python -u "+test['rem_test_path']+" --verbose"

            cmd = pre_cmd + wd_cmd + cmd_test
            log.debug("Run: "+str(cmd))

                _, stdout, stderr = self.ssh_cons.exec_command(cmd)

                if stdout:
                    output = stdout.readlines()
                    raw_out = "".join(output)
          "-==== DETAILED LOG ====-")

                if stderr:
                    output = stderr.readlines()
                    raw_out = "".join(output)
          "-==== UNITTEST LOG ====-")
                log.error("Test execution command cannot run: "+str(cmd))

        if progressbar:
            pass"-==== END OF RELATED TESTS EXECUTION ====-")


So the problem solved, partially. 

Still wondering – how to make progressbar or spinner update constantly till process not die?

About trianglesis

Александр Брюндтзвельт - гений, филантроп, 100 гривен в кармане. Этот блог - "сток" моих мыслей и заметок. Достаточно одного взгляда на него, чтобы понять, что такой же бардак творится у меня в голове. Если вам этот бардак интересен - милости прошу.
Bookmark the permalink.

Comments are closed.