[Python-3000-checkins] r58957 - python/branches/py3k/Demo/curses/repeat.py

guido.van.rossum python-3000-checkins at python.org
Tue Nov 13 00:12:57 CET 2007


Author: guido.van.rossum
Date: Tue Nov 13 00:12:57 2007
New Revision: 58957

Modified:
   python/branches/py3k/Demo/curses/repeat.py
Log:
Add -i option.  Don't exit when the command fails.  Redirect stderr to stdout.


Modified: python/branches/py3k/Demo/curses/repeat.py
==============================================================================
--- python/branches/py3k/Demo/curses/repeat.py	(original)
+++ python/branches/py3k/Demo/curses/repeat.py	Tue Nov 13 00:12:57 2007
@@ -1,6 +1,6 @@
 #! /usr/bin/env python
 
-"""repeat <shell-command>
+"""repeat [-i SECONDS] <shell-command>
 
 This simple program repeatedly (at 1-second intervals) executes the
 shell command given on the command line and displays the output (or as
@@ -9,6 +9,8 @@
 screen doesn't change.  This is handy to watch for changes in e.g. a
 directory or process listing.
 
+The -i option lets you override the sleep time between executions.
+
 To end, hit Control-C.
 """
 
@@ -24,18 +26,30 @@
 import sys
 import time
 import curses
+import getopt
 
 def main():
-    if not sys.argv[1:]:
+    interval = 1.0
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], "hi:")
+    except getopt.error as err:
+        print(err, file=sys.stderr)
+        sys.exit(2)
+    if not args:
         print(__doc__)
         sys.exit(0)
-    cmd = " ".join(sys.argv[1:])
-    p = os.popen(cmd, "r")
+    for opt, arg in opts:
+        if opt == "-i":
+            interval = float(arg)
+        if opt == "-h":
+            print(__doc__)
+            sys.exit(0)
+    cmd = " ".join(args)
+    cmd_really = cmd + " 2>&1"
+    p = os.popen(cmd_really, "r")
     text = p.read()
     sts = p.close()
-    if sts:
-        print("Exit code:", sts, file=sys.stderr)
-        sys.exit(sts)
+    text = addsts(interval, cmd, text, sts)
     w = curses.initscr()
     try:
         while True:
@@ -45,14 +59,22 @@
             except curses.error:
                 pass
             w.refresh()
-            time.sleep(1)
-            p = os.popen(cmd, "r")
+            time.sleep(interval)
+            p = os.popen(cmd_really, "r")
             text = p.read()
             sts = p.close()
-            if sts:
-                print("Exit code:", sts, file=sys.stderr)
-                sys.exit(sts)
+            text = addsts(interval, cmd, text, sts)
     finally:
         curses.endwin()
 
+def addsts(interval, cmd, text, sts):
+    now = time.strftime("%H:%M:%S")
+    text = "%s, every %g sec: %s\n%s" % (now, interval, cmd, text)
+    if sts:
+        msg = "Exit status: %d; signal: %d" % (sts>>8, sts&0xFF)
+        if text and not text.endswith("\n"):
+            msg = "\n" + msg
+        text += msg
+    return text
+
 main()


More information about the Python-3000-checkins mailing list