d376ed4aeeae97590ff18e7e90b08bdd8c4c2640
[archive/20170607/tools/tic-core.git] / tic / utils / process.py
1 #!/usr/bin/python
2 # Copyright (c) 2000 - 2016 Samsung Electronics Co., Ltd. All rights reserved.
3 #
4 # Contact: 
5 # @author Chulwoo Shin <cw1.shin@samsung.com>
6
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 #
19 # Contributors:
20 # - S-Core Co., Ltd
21
22 import os
23 import subprocess
24 import logging
25
26 from tic.utils.error import TICError
27
28 def run(cmdln, catch=3):
29     logger = logging.getLogger(__name__)
30     if isinstance(cmdln, list):
31         cmd = cmdln[0]
32         shellType = False
33     else:
34         import shlex
35         cmd = shlex.split(cmdln)[0]
36         shellType = True
37         
38         
39     if catch == 0:
40         # silent run
41         dev_null = os.open("/dev/null", os.O_WRONLY)
42         sout = dev_null
43         serr = dev_null
44     elif catch == 2:
45         # no redirection
46         sout = None
47         serr = None
48     elif catch == 3:
49         # both STDOUT and STDERR
50         sout = subprocess.PIPE
51         serr = subprocess.STDOUT
52     
53     try:
54         logger.info('subprocess open: %s', cmd)
55         p = subprocess.Popen(cmdln, 
56                              stdout=sout,
57                              stderr=serr,
58                              shell=shellType)
59
60         (sout, serr) = p.communicate()
61         out = ''.join(filter(None, [sout, serr]))
62     except OSError as e:
63         if e.errno == 2:
64             # No such file or directory
65             raise TICError('Cannot run command: %s' % cmd)
66         else:
67             raise
68     finally:
69         if catch == 0:
70             os.close(dev_null)
71
72     return (p.returncode, out)