From 17cb8c455076d444e6068b8ae394de3fde1e7dc1 Mon Sep 17 00:00:00 2001 From: winlin Date: Wed, 11 Jun 2014 11:14:43 +0800 Subject: [PATCH] finish the research for python-subprocess --- trunk/research/python-subprocess/main.py | 52 ++++++++++++------------ 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/trunk/research/python-subprocess/main.py b/trunk/research/python-subprocess/main.py index afd67ca81..81df4270b 100755 --- a/trunk/research/python-subprocess/main.py +++ b/trunk/research/python-subprocess/main.py @@ -1,17 +1,20 @@ #!/usr/bin/python # -*- coding: utf-8 -*- - -import sys, shlex, time, subprocess - -cmd = "./python.subprocess 0 800" -args = shlex.split(str(cmd)) -print "cmd: %s, args: %s"%(cmd, args) - -def use_communicate(args, fout, ferr): - process = subprocess.Popen(args, stdout=fout, stderr=ferr) + +import sys, shlex, time, subprocess + +cmd = "./python.subprocess 0 80000" +args = shlex.split(str(cmd)) +print "cmd: %s, args: %s"%(cmd, args) + +# the communicate will read all data and wait for sub process to quit. +def use_communicate(args, fout, ferr): + process = subprocess.Popen(args, stdout=fout, stderr=ferr) (stdout_str, stderr_str) = process.communicate() return (stdout_str, stderr_str) +# if use subprocess.PIPE, the pipe will full about 50KB data, +# and sub process will blocked, then timeout will kill it. def use_poll(args, fout, ferr, timeout): (stdout_str, stderr_str) = (None, None) process = subprocess.Popen(args, stdout=fout, stderr=ferr) @@ -28,27 +31,22 @@ def use_poll(args, fout, ferr, timeout): time.sleep(1) process.wait() return (stdout_str, stderr_str) -def use_communicate_timeout(args, fout, ferr, timeout): - (stdout_str, stderr_str) = (None, None) - process = subprocess.Popen(args, stdout=fout, stderr=ferr) - starttime = time.time() - while True: -fnull = open("/dev/null", "rw") -fout = subprocess.PIPE#fnull.fileno() -ferr = subprocess.PIPE#fnull#fnull.fileno() -print "fout=%s, ferr=%s"%(fout, ferr) +# stdout/stderr can be fd, fileobject, subprocess.PIPE, None +fnull = open("/dev/null", "rw") +fout = fnull.fileno()#subprocess.PIPE#fnull#fnull.fileno() +ferr = fnull.fileno()#subprocess.PIPE#fnull#fnull.fileno() +print "fout=%s, ferr=%s"%(fout, ferr) #(stdout_str, stderr_str) = use_communicate(args, fout, ferr) -#(stdout_str, stderr_str) = use_poll(args, fout, ferr, 10) -(stdout_str, stderr_str) = use_communicate_timeout(args, fout, ferr, 10) +(stdout_str, stderr_str) = use_poll(args, fout, ferr, 10) -def print_result(stdout_str, stderr_str): - if stdout_str is None: - stdout_str = "" - if stderr_str is None: - stderr_str = "" +def print_result(stdout_str, stderr_str): + if stdout_str is None: + stdout_str = "" + if stderr_str is None: + stderr_str = "" print "terminated, size of stdout=%s, stderr=%s"%(len(stdout_str), len(stderr_str)) - while True: - time.sleep(1) + while True: + time.sleep(1) print_result(stdout_str, stderr_str)