1. Vinay Sajip
  2. docs-sarge

Commits

Vinay Sajip  committed 057753d Draft

Routine update.

  • Participants
  • Parent commits d43db1c
  • Branches default

Comments (0)

Files changed (1)

File docs/tutorial.rst

View file
     'line 100'
 
 
+Displaying progress as a subprocess runs
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+You can display progress as a sub-process runs, assuming that its output
+allows you to track that progress. Consider the following script,
+``progress.py``::
+
+    import optparse # because of 2.6 support
+    import sys
+    import threading
+    import time
+
+    from sarge import Capture, capture_stdout
+
+    def progress(capture, options):
+        lines_seen = 0
+        messages = {
+            'line 25\n': 'Getting going ...\n',
+            'line 50\n': 'Well on the way ...\n',
+            'line 75\n': 'Almost there ...\n',
+        }
+        while True:
+            s = capture.readline()
+            if not s and lines_seen:
+                break
+            if options.dots:
+                sys.stderr.write('.')
+            else:
+                msg = messages.get(s)
+                if msg:
+                    sys.stderr.write(msg)
+            lines_seen += 1
+        if options.dots:
+            sys.stderr.write('\n')
+        sys.stderr.write('Done - %d lines seen.\n' % lines_seen)
+
+    def main():
+        parser = optparse.OptionParser()
+        parser.add_option('-n', '--no-dots', dest='dots', default=True,
+                          action='store_false', help='Show dots for progress')
+        options, args = parser.parse_args()
+        p = capture_stdout('python lister.py -d 0.1 -c 100', async=True)
+        t = threading.Thread(target=progress, args=(p.stdout, options))
+        t.start()
+        while(p.returncodes[0] is None):
+            # We could do other useful work here.
+            p.commands[0].poll()
+            time.sleep(0.05)
+        t.join()
+
+    if __name__ == '__main__':
+        sys.exit(main())
+
+When this is run without the ``--no-dots`` argument, you should see the
+following::
+
+    $ python progress.py
+    ....................................................................................................
+    Done - 100 lines seen.
+
+If run with the ``--no-dots`` argument, you should see::
+
+    $ python progress.py --no-dots
+    Getting going ...
+    Well on the way ...
+    Almost there ...
+    Done - 100 lines seen.
+
+with short pauses between the output lines.
+
+
 Direct terminal usage
 ^^^^^^^^^^^^^^^^^^^^^