I am trying to write a simple version of the time command-line program in Python, except that instead of mapping real / usr / sys time to the shell, it writes it to the database.
I currently have:
wrapper.py
#!/usr/bin/python import sys from subprocess import Popen, PIPE cmd = 'time ' + (' '.join(['"%s"' % v if ' ' in v else v for v in sys.argv[1:]])) p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) print p.stdout.read() print p.stderr.read()
For simplicity, I excluded the database insert code.
However, to illustrate the problem, I use a test script:
#!/usr/bin/python import time for i in xrange(3): print i time.sleep(1)
If I ran wrapper.py python delay.py , I would like the seconds to be displayed in real time, and then something like:
real 0m3.057s user 0m0.030s sys 0m0.000s
Instead, I don't get output for 3 seconds, and then it prints:
0 1 2 0.02user 0.00system 0:03.03elapsed 0%CPU (0avgtext+0avgdata 21632maxresident)k 0inputs+0outputs (0major+1514minor)pagefaults 0swaps
How do you read and print output from a subprocess, how does this happen in real time?
Also, why is the output from time different than when I run it directly in the shell and get messed up when running from a subprocess inside a Python script?