exec_command.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. """
  2. exec_command
  3. Implements exec_command function that is (almost) equivalent to
  4. commands.getstatusoutput function but on NT, DOS systems the
  5. returned status is actually correct (though, the returned status
  6. values may be different by a factor). In addition, exec_command
  7. takes keyword arguments for (re-)defining environment variables.
  8. Provides functions:
  9. exec_command --- execute command in a specified directory and
  10. in the modified environment.
  11. find_executable --- locate a command using info from environment
  12. variable PATH. Equivalent to posix `which`
  13. command.
  14. Author: Pearu Peterson <pearu@cens.ioc.ee>
  15. Created: 11 January 2003
  16. Requires: Python 2.x
  17. Successfully tested on:
  18. ======== ============ =================================================
  19. os.name sys.platform comments
  20. ======== ============ =================================================
  21. posix linux2 Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3
  22. PyCrust 0.9.3, Idle 1.0.2
  23. posix linux2 Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2
  24. posix sunos5 SunOS 5.9, Python 2.2, 2.3.2
  25. posix darwin Darwin 7.2.0, Python 2.3
  26. nt win32 Windows Me
  27. Python 2.3(EE), Idle 1.0, PyCrust 0.7.2
  28. Python 2.1.1 Idle 0.8
  29. nt win32 Windows 98, Python 2.1.1. Idle 0.8
  30. nt win32 Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests
  31. fail i.e. redefining environment variables may
  32. not work. FIXED: don't use cygwin echo!
  33. Comment: also `cmd /c echo` will not work
  34. but redefining environment variables do work.
  35. posix cygwin Cygwin 98-4.10, Python 2.3.3(cygming special)
  36. nt win32 Windows XP, Python 2.3.3
  37. ======== ============ =================================================
  38. Known bugs:
  39. * Tests, that send messages to stderr, fail when executed from MSYS prompt
  40. because the messages are lost at some point.
  41. """
  42. from __future__ import division, absolute_import, print_function
  43. __all__ = ['exec_command', 'find_executable']
  44. import os
  45. import sys
  46. import subprocess
  47. import locale
  48. from numpy.distutils.misc_util import is_sequence, make_temp_file
  49. from numpy.distutils import log
  50. def filepath_from_subprocess_output(output):
  51. """
  52. Convert `bytes` in the encoding used by a subprocess into a filesystem-appropriate `str`.
  53. Inherited from `exec_command`, and possibly incorrect.
  54. """
  55. mylocale = locale.getpreferredencoding(False)
  56. if mylocale is None:
  57. mylocale = 'ascii'
  58. output = output.decode(mylocale, errors='replace')
  59. output = output.replace('\r\n', '\n')
  60. # Another historical oddity
  61. if output[-1:] == '\n':
  62. output = output[:-1]
  63. # stdio uses bytes in python 2, so to avoid issues, we simply
  64. # remove all non-ascii characters
  65. if sys.version_info < (3, 0):
  66. output = output.encode('ascii', errors='replace')
  67. return output
  68. def forward_bytes_to_stdout(val):
  69. """
  70. Forward bytes from a subprocess call to the console, without attempting to
  71. decode them.
  72. The assumption is that the subprocess call already returned bytes in
  73. a suitable encoding.
  74. """
  75. if sys.version_info.major < 3:
  76. # python 2 has binary output anyway
  77. sys.stdout.write(val)
  78. elif hasattr(sys.stdout, 'buffer'):
  79. # use the underlying binary output if there is one
  80. sys.stdout.buffer.write(val)
  81. elif hasattr(sys.stdout, 'encoding'):
  82. # round-trip the encoding if necessary
  83. sys.stdout.write(val.decode(sys.stdout.encoding))
  84. else:
  85. # make a best-guess at the encoding
  86. sys.stdout.write(val.decode('utf8', errors='replace'))
  87. def temp_file_name():
  88. fo, name = make_temp_file()
  89. fo.close()
  90. return name
  91. def get_pythonexe():
  92. pythonexe = sys.executable
  93. if os.name in ['nt', 'dos']:
  94. fdir, fn = os.path.split(pythonexe)
  95. fn = fn.upper().replace('PYTHONW', 'PYTHON')
  96. pythonexe = os.path.join(fdir, fn)
  97. assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,)
  98. return pythonexe
  99. def find_executable(exe, path=None, _cache={}):
  100. """Return full path of a executable or None.
  101. Symbolic links are not followed.
  102. """
  103. key = exe, path
  104. try:
  105. return _cache[key]
  106. except KeyError:
  107. pass
  108. log.debug('find_executable(%r)' % exe)
  109. orig_exe = exe
  110. if path is None:
  111. path = os.environ.get('PATH', os.defpath)
  112. if os.name=='posix':
  113. realpath = os.path.realpath
  114. else:
  115. realpath = lambda a:a
  116. if exe.startswith('"'):
  117. exe = exe[1:-1]
  118. suffixes = ['']
  119. if os.name in ['nt', 'dos', 'os2']:
  120. fn, ext = os.path.splitext(exe)
  121. extra_suffixes = ['.exe', '.com', '.bat']
  122. if ext.lower() not in extra_suffixes:
  123. suffixes = extra_suffixes
  124. if os.path.isabs(exe):
  125. paths = ['']
  126. else:
  127. paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]
  128. for path in paths:
  129. fn = os.path.join(path, exe)
  130. for s in suffixes:
  131. f_ext = fn+s
  132. if not os.path.islink(f_ext):
  133. f_ext = realpath(f_ext)
  134. if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):
  135. log.info('Found executable %s' % f_ext)
  136. _cache[key] = f_ext
  137. return f_ext
  138. log.warn('Could not locate executable %s' % orig_exe)
  139. return None
  140. ############################################################
  141. def _preserve_environment( names ):
  142. log.debug('_preserve_environment(%r)' % (names))
  143. env = {name: os.environ.get(name) for name in names}
  144. return env
  145. def _update_environment( **env ):
  146. log.debug('_update_environment(...)')
  147. for name, value in env.items():
  148. os.environ[name] = value or ''
  149. def _supports_fileno(stream):
  150. """
  151. Returns True if 'stream' supports the file descriptor and allows fileno().
  152. """
  153. if hasattr(stream, 'fileno'):
  154. try:
  155. stream.fileno()
  156. return True
  157. except IOError:
  158. return False
  159. else:
  160. return False
  161. def exec_command(command, execute_in='', use_shell=None, use_tee=None,
  162. _with_python = 1, **env ):
  163. """
  164. Return (status,output) of executed command.
  165. Parameters
  166. ----------
  167. command : str
  168. A concatenated string of executable and arguments.
  169. execute_in : str
  170. Before running command ``cd execute_in`` and after ``cd -``.
  171. use_shell : {bool, None}, optional
  172. If True, execute ``sh -c command``. Default None (True)
  173. use_tee : {bool, None}, optional
  174. If True use tee. Default None (True)
  175. Returns
  176. -------
  177. res : str
  178. Both stdout and stderr messages.
  179. Notes
  180. -----
  181. On NT, DOS systems the returned status is correct for external commands.
  182. Wild cards will not work for non-posix systems or when use_shell=0.
  183. """
  184. log.debug('exec_command(%r,%s)' % (command,\
  185. ','.join(['%s=%r'%kv for kv in env.items()])))
  186. if use_tee is None:
  187. use_tee = os.name=='posix'
  188. if use_shell is None:
  189. use_shell = os.name=='posix'
  190. execute_in = os.path.abspath(execute_in)
  191. oldcwd = os.path.abspath(os.getcwd())
  192. if __name__[-12:] == 'exec_command':
  193. exec_dir = os.path.dirname(os.path.abspath(__file__))
  194. elif os.path.isfile('exec_command.py'):
  195. exec_dir = os.path.abspath('.')
  196. else:
  197. exec_dir = os.path.abspath(sys.argv[0])
  198. if os.path.isfile(exec_dir):
  199. exec_dir = os.path.dirname(exec_dir)
  200. if oldcwd!=execute_in:
  201. os.chdir(execute_in)
  202. log.debug('New cwd: %s' % execute_in)
  203. else:
  204. log.debug('Retaining cwd: %s' % oldcwd)
  205. oldenv = _preserve_environment( list(env.keys()) )
  206. _update_environment( **env )
  207. try:
  208. st = _exec_command(command,
  209. use_shell=use_shell,
  210. use_tee=use_tee,
  211. **env)
  212. finally:
  213. if oldcwd!=execute_in:
  214. os.chdir(oldcwd)
  215. log.debug('Restored cwd to %s' % oldcwd)
  216. _update_environment(**oldenv)
  217. return st
  218. def _exec_command(command, use_shell=None, use_tee = None, **env):
  219. """
  220. Internal workhorse for exec_command().
  221. """
  222. if use_shell is None:
  223. use_shell = os.name=='posix'
  224. if use_tee is None:
  225. use_tee = os.name=='posix'
  226. if os.name == 'posix' and use_shell:
  227. # On POSIX, subprocess always uses /bin/sh, override
  228. sh = os.environ.get('SHELL', '/bin/sh')
  229. if is_sequence(command):
  230. command = [sh, '-c', ' '.join(command)]
  231. else:
  232. command = [sh, '-c', command]
  233. use_shell = False
  234. elif os.name == 'nt' and is_sequence(command):
  235. # On Windows, join the string for CreateProcess() ourselves as
  236. # subprocess does it a bit differently
  237. command = ' '.join(_quote_arg(arg) for arg in command)
  238. # Inherit environment by default
  239. env = env or None
  240. try:
  241. # universal_newlines is set to False so that communicate()
  242. # will return bytes. We need to decode the output ourselves
  243. # so that Python will not raise a UnicodeDecodeError when
  244. # it encounters an invalid character; rather, we simply replace it
  245. proc = subprocess.Popen(command, shell=use_shell, env=env,
  246. stdout=subprocess.PIPE,
  247. stderr=subprocess.STDOUT,
  248. universal_newlines=False)
  249. except EnvironmentError:
  250. # Return 127, as os.spawn*() and /bin/sh do
  251. return 127, ''
  252. text, err = proc.communicate()
  253. mylocale = locale.getpreferredencoding(False)
  254. if mylocale is None:
  255. mylocale = 'ascii'
  256. text = text.decode(mylocale, errors='replace')
  257. text = text.replace('\r\n', '\n')
  258. # Another historical oddity
  259. if text[-1:] == '\n':
  260. text = text[:-1]
  261. # stdio uses bytes in python 2, so to avoid issues, we simply
  262. # remove all non-ascii characters
  263. if sys.version_info < (3, 0):
  264. text = text.encode('ascii', errors='replace')
  265. if use_tee and text:
  266. print(text)
  267. return proc.returncode, text
  268. def _quote_arg(arg):
  269. """
  270. Quote the argument for safe use in a shell command line.
  271. """
  272. # If there is a quote in the string, assume relevants parts of the
  273. # string are already quoted (e.g. '-I"C:\\Program Files\\..."')
  274. if '"' not in arg and ' ' in arg:
  275. return '"%s"' % arg
  276. return arg
  277. ############################################################