exec_command.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. __all__ = ['exec_command', 'find_executable']
  43. import os
  44. import sys
  45. import subprocess
  46. import locale
  47. import warnings
  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. return output
  64. def forward_bytes_to_stdout(val):
  65. """
  66. Forward bytes from a subprocess call to the console, without attempting to
  67. decode them.
  68. The assumption is that the subprocess call already returned bytes in
  69. a suitable encoding.
  70. """
  71. if hasattr(sys.stdout, 'buffer'):
  72. # use the underlying binary output if there is one
  73. sys.stdout.buffer.write(val)
  74. elif hasattr(sys.stdout, 'encoding'):
  75. # round-trip the encoding if necessary
  76. sys.stdout.write(val.decode(sys.stdout.encoding))
  77. else:
  78. # make a best-guess at the encoding
  79. sys.stdout.write(val.decode('utf8', errors='replace'))
  80. def temp_file_name():
  81. # 2019-01-30, 1.17
  82. warnings.warn('temp_file_name is deprecated since NumPy v1.17, use '
  83. 'tempfile.mkstemp instead', DeprecationWarning, stacklevel=1)
  84. fo, name = make_temp_file()
  85. fo.close()
  86. return name
  87. def get_pythonexe():
  88. pythonexe = sys.executable
  89. if os.name in ['nt', 'dos']:
  90. fdir, fn = os.path.split(pythonexe)
  91. fn = fn.upper().replace('PYTHONW', 'PYTHON')
  92. pythonexe = os.path.join(fdir, fn)
  93. assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,)
  94. return pythonexe
  95. def find_executable(exe, path=None, _cache={}):
  96. """Return full path of a executable or None.
  97. Symbolic links are not followed.
  98. """
  99. key = exe, path
  100. try:
  101. return _cache[key]
  102. except KeyError:
  103. pass
  104. log.debug('find_executable(%r)' % exe)
  105. orig_exe = exe
  106. if path is None:
  107. path = os.environ.get('PATH', os.defpath)
  108. if os.name=='posix':
  109. realpath = os.path.realpath
  110. else:
  111. realpath = lambda a:a
  112. if exe.startswith('"'):
  113. exe = exe[1:-1]
  114. suffixes = ['']
  115. if os.name in ['nt', 'dos', 'os2']:
  116. fn, ext = os.path.splitext(exe)
  117. extra_suffixes = ['.exe', '.com', '.bat']
  118. if ext.lower() not in extra_suffixes:
  119. suffixes = extra_suffixes
  120. if os.path.isabs(exe):
  121. paths = ['']
  122. else:
  123. paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]
  124. for path in paths:
  125. fn = os.path.join(path, exe)
  126. for s in suffixes:
  127. f_ext = fn+s
  128. if not os.path.islink(f_ext):
  129. f_ext = realpath(f_ext)
  130. if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):
  131. log.info('Found executable %s' % f_ext)
  132. _cache[key] = f_ext
  133. return f_ext
  134. log.warn('Could not locate executable %s' % orig_exe)
  135. return None
  136. ############################################################
  137. def _preserve_environment( names ):
  138. log.debug('_preserve_environment(%r)' % (names))
  139. env = {name: os.environ.get(name) for name in names}
  140. return env
  141. def _update_environment( **env ):
  142. log.debug('_update_environment(...)')
  143. for name, value in env.items():
  144. os.environ[name] = value or ''
  145. def exec_command(command, execute_in='', use_shell=None, use_tee=None,
  146. _with_python = 1, **env ):
  147. """
  148. Return (status,output) of executed command.
  149. .. deprecated:: 1.17
  150. Use subprocess.Popen instead
  151. Parameters
  152. ----------
  153. command : str
  154. A concatenated string of executable and arguments.
  155. execute_in : str
  156. Before running command ``cd execute_in`` and after ``cd -``.
  157. use_shell : {bool, None}, optional
  158. If True, execute ``sh -c command``. Default None (True)
  159. use_tee : {bool, None}, optional
  160. If True use tee. Default None (True)
  161. Returns
  162. -------
  163. res : str
  164. Both stdout and stderr messages.
  165. Notes
  166. -----
  167. On NT, DOS systems the returned status is correct for external commands.
  168. Wild cards will not work for non-posix systems or when use_shell=0.
  169. """
  170. # 2019-01-30, 1.17
  171. warnings.warn('exec_command is deprecated since NumPy v1.17, use '
  172. 'subprocess.Popen instead', DeprecationWarning, stacklevel=1)
  173. log.debug('exec_command(%r,%s)' % (command,
  174. ','.join(['%s=%r'%kv for kv in env.items()])))
  175. if use_tee is None:
  176. use_tee = os.name=='posix'
  177. if use_shell is None:
  178. use_shell = os.name=='posix'
  179. execute_in = os.path.abspath(execute_in)
  180. oldcwd = os.path.abspath(os.getcwd())
  181. if __name__[-12:] == 'exec_command':
  182. exec_dir = os.path.dirname(os.path.abspath(__file__))
  183. elif os.path.isfile('exec_command.py'):
  184. exec_dir = os.path.abspath('.')
  185. else:
  186. exec_dir = os.path.abspath(sys.argv[0])
  187. if os.path.isfile(exec_dir):
  188. exec_dir = os.path.dirname(exec_dir)
  189. if oldcwd!=execute_in:
  190. os.chdir(execute_in)
  191. log.debug('New cwd: %s' % execute_in)
  192. else:
  193. log.debug('Retaining cwd: %s' % oldcwd)
  194. oldenv = _preserve_environment( list(env.keys()) )
  195. _update_environment( **env )
  196. try:
  197. st = _exec_command(command,
  198. use_shell=use_shell,
  199. use_tee=use_tee,
  200. **env)
  201. finally:
  202. if oldcwd!=execute_in:
  203. os.chdir(oldcwd)
  204. log.debug('Restored cwd to %s' % oldcwd)
  205. _update_environment(**oldenv)
  206. return st
  207. def _exec_command(command, use_shell=None, use_tee = None, **env):
  208. """
  209. Internal workhorse for exec_command().
  210. """
  211. if use_shell is None:
  212. use_shell = os.name=='posix'
  213. if use_tee is None:
  214. use_tee = os.name=='posix'
  215. if os.name == 'posix' and use_shell:
  216. # On POSIX, subprocess always uses /bin/sh, override
  217. sh = os.environ.get('SHELL', '/bin/sh')
  218. if is_sequence(command):
  219. command = [sh, '-c', ' '.join(command)]
  220. else:
  221. command = [sh, '-c', command]
  222. use_shell = False
  223. elif os.name == 'nt' and is_sequence(command):
  224. # On Windows, join the string for CreateProcess() ourselves as
  225. # subprocess does it a bit differently
  226. command = ' '.join(_quote_arg(arg) for arg in command)
  227. # Inherit environment by default
  228. env = env or None
  229. try:
  230. # universal_newlines is set to False so that communicate()
  231. # will return bytes. We need to decode the output ourselves
  232. # so that Python will not raise a UnicodeDecodeError when
  233. # it encounters an invalid character; rather, we simply replace it
  234. proc = subprocess.Popen(command, shell=use_shell, env=env,
  235. stdout=subprocess.PIPE,
  236. stderr=subprocess.STDOUT,
  237. universal_newlines=False)
  238. except EnvironmentError:
  239. # Return 127, as os.spawn*() and /bin/sh do
  240. return 127, ''
  241. text, err = proc.communicate()
  242. mylocale = locale.getpreferredencoding(False)
  243. if mylocale is None:
  244. mylocale = 'ascii'
  245. text = text.decode(mylocale, errors='replace')
  246. text = text.replace('\r\n', '\n')
  247. # Another historical oddity
  248. if text[-1:] == '\n':
  249. text = text[:-1]
  250. if use_tee and text:
  251. print(text)
  252. return proc.returncode, text
  253. def _quote_arg(arg):
  254. """
  255. Quote the argument for safe use in a shell command line.
  256. """
  257. # If there is a quote in the string, assume relevants parts of the
  258. # string are already quoted (e.g. '-I"C:\\Program Files\\..."')
  259. if '"' not in arg and ' ' in arg:
  260. return '"%s"' % arg
  261. return arg
  262. ############################################################