[TIC-CORE] support cli commands
[archive/20170607/tools/tic-core.git] / tic / utils / process.py
index 7d02125..d376ed4 100644 (file)
 # Contributors:
 # - S-Core Co., Ltd
 
+import os
 import subprocess
+import logging
 
 from tic.utils.error import TICError
 
-def run(cmdln):
+def run(cmdln, catch=3):
+    logger = logging.getLogger(__name__)
     if isinstance(cmdln, list):
         cmd = cmdln[0]
         shellType = False
@@ -31,12 +34,29 @@ def run(cmdln):
         import shlex
         cmd = shlex.split(cmdln)[0]
         shellType = True
+        
+        
+    if catch == 0:
+        # silent run
+        dev_null = os.open("/dev/null", os.O_WRONLY)
+        sout = dev_null
+        serr = dev_null
+    elif catch == 2:
+        # no redirection
+        sout = None
+        serr = None
+    elif catch == 3:
+        # both STDOUT and STDERR
+        sout = subprocess.PIPE
+        serr = subprocess.STDOUT
     
     try:
+        logger.info('subprocess open: %s', cmd)
         p = subprocess.Popen(cmdln, 
-                             stdout=subprocess.PIPE,
-                             stderr=subprocess.PIPE,
+                             stdout=sout,
+                             stderr=serr,
                              shell=shellType)
+
         (sout, serr) = p.communicate()
         out = ''.join(filter(None, [sout, serr]))
     except OSError as e:
@@ -45,6 +65,8 @@ def run(cmdln):
             raise TICError('Cannot run command: %s' % cmd)
         else:
             raise
+    finally:
+        if catch == 0:
+            os.close(dev_null)
 
-    return (p.returncode, out)
-
+    return (p.returncode, out)
\ No newline at end of file