On 01/14/2014 10:29 AM, Shu Ming wrote:
It seems that python 3.3 has supported this function in a native way.
I think we can add some code to use the native one if it has like this
import sys
import subprocess
def run_command(cmd, timeout=None):
if sys.hexversion >= 0x03030000:
return partial(subprocess.call, ...)
else:
...
not sure we should support python3.3
some syntax difference between python3.3 and python2.7
such as print:
in python3
$ python3.3 -c 'print("hello")'
hello
in python2
$ python2.7 -c 'print "hello"'
hello
2014/1/10 22:10, shaohef(a)linux.vnet.ibm.com:
> From: ShaoHe Feng <shaohef(a)linux.vnet.ibm.com>
>
> We need a common function to execute shell command.
> We also need timeout when execute shell command.
>
> A threading.Timer is used to send signal.SIGKILL to kill the command
> when timeout.
>
> Signed-off-by: Royce Lv <lvroyce(a)linux.vnet.ibm.com>
> Signed-off-by: ShaoHe Feng <shaohef(a)linux.vnet.ibm.com>
> ---
> src/kimchi/utils.py | 43 +++++++++++++++++++++++++++++++++++++++++++
> 1 file changed, 43 insertions(+)
>
> diff --git a/src/kimchi/utils.py b/src/kimchi/utils.py
> index af245c6..c7165ce 100644
> --- a/src/kimchi/utils.py
> +++ b/src/kimchi/utils.py
> @@ -23,6 +23,7 @@
>
> import cherrypy
> import os
> +import subprocess
> import urllib2
>
>
> @@ -30,6 +31,7 @@ from cherrypy.lib.reprconf import Parser
>
>
> from kimchi import config
> +from threading import Timer
>
>
> kimchi_log = cherrypy.log.error_log
> @@ -96,3 +98,44 @@ def check_url_path(path):
> return False
>
> return True
> +
> +
> +def run_command(cmd, timeout=None):
> + def kill_proc(proc, timeout_flag):
> + timeout_flag[0] = True
> + proc.kill()
> +
> + proc = None
> + timer = None
> + timeout_flag = [False]
> +
> + try:
> + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
> + stderr=subprocess.PIPE)
> + if timeout is not None:
> + timer = Timer(timeout, kill_proc, [proc, timeout_flag])
> + timer.start()
> +
> + out, error = proc.communicate()
> + kimchi_log.debug("Run command: '%s'", " ".join(cmd))
> +
> + if out or error:
> + kimchi_log.debug("out:\n %s\nerror:\n %s", out, error)
> +
> + if proc.returncode == -9 and timeout_flag[0] is True:
> + kimchi_log.error("subprocess is killed by signal.SIGKILL "
> + "for timeout %s seconds", timeout)
> +
> + return out, error, proc.returncode, timeout_flag[0]
> + except Exception as e:
> + msg = "Failed to run command: %s." % " ".join(cmd)
> + msg = msg if proc is None else msg + "\n error code: %s."
> + kimchi_log.error("%s\n %s", msg, e)
> +
> + if proc:
> + return out, error, proc.returncode, timeout_flag[0]
> + else:
> + return None, None, None, timeout_flag[0]
> + finally:
> + if timer and not timeout_flag[0]:
> + timer.cancel()
--
Thanks and best regards!
Sheldon Feng(冯少合)<shaohef(a)linux.vnet.ibm.com>
IBM Linux Technology Center