waf/waflib/extras/print_commands.py

83 lines
1.9 KiB
Python
Raw Normal View History

2011-11-19 18:31:23 +01:00
#! /usr/bin/env python
"""
Illustrate how to override a class method to do something
In this case, print the commands being executed as strings
(the commands are usually lists, so this can be misleading)
"""
2011-12-17 22:42:17 +01:00
import sys
from waflib import Context, Utils, Errors, Logs
2011-11-19 18:31:23 +01:00
def exec_command(self, cmd, **kw):
subprocess = Utils.subprocess
kw['shell'] = isinstance(cmd, str)
if isinstance(cmd, str):
kw['shell'] = True
txt = cmd
else:
txt = ' '.join(repr(x) if ' ' in x else x for x in cmd)
2011-11-19 18:31:23 +01:00
Logs.debug('runner: %s', txt)
Logs.debug('runner_env: kw=%s', kw)
2011-11-19 18:31:23 +01:00
if self.logger:
self.logger.info(cmd)
if 'stdout' not in kw:
kw['stdout'] = subprocess.PIPE
if 'stderr' not in kw:
kw['stderr'] = subprocess.PIPE
2011-11-19 18:31:23 +01:00
if Logs.verbose and not kw['shell'] and not Utils.check_exe(cmd[0]):
raise Errors.WafError("Program %s not found!" % cmd[0])
2011-11-19 18:31:23 +01:00
wargs = {}
if 'timeout' in kw:
if kw['timeout'] is not None:
wargs['timeout'] = kw['timeout']
del kw['timeout']
if 'input' in kw:
if kw['input']:
wargs['input'] = kw['input']
kw['stdin'] = Utils.subprocess.PIPE
del kw['input']
2016-01-11 05:25:46 +01:00
if 'cwd' in kw:
if not isinstance(kw['cwd'], str):
kw['cwd'] = kw['cwd'].abspath()
try:
if kw['stdout'] or kw['stderr']:
2011-11-19 18:31:23 +01:00
p = subprocess.Popen(cmd, **kw)
(out, err) = p.communicate(**wargs)
ret = p.returncode
2011-11-19 18:31:23 +01:00
else:
out, err = (None, None)
ret = subprocess.Popen(cmd, **kw).wait(**wargs)
except Exception as e:
raise Errors.WafError('Execution failure: %s' % str(e), ex=e)
if out:
if not isinstance(out, str):
2017-01-21 13:28:06 +01:00
out = out.decode(sys.stdout.encoding or 'latin-1')
if self.logger:
self.logger.debug('out: %s' % out)
else:
Logs.info(out, extra={'stream':sys.stdout, 'c1': ''})
if err:
if not isinstance(err, str):
2017-01-21 13:28:06 +01:00
err = err.decode(sys.stdout.encoding or 'latin-1')
if self.logger:
self.logger.error('err: %s' % err)
else:
Logs.info(err, extra={'stream':sys.stderr, 'c1': ''})
return ret
2011-11-19 18:31:23 +01:00
Context.Context.exec_command = exec_command