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