_shell_utils.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """
  2. Helper functions for interacting with the shell, and consuming shell-style
  3. parameters provided in config files.
  4. """
  5. import os
  6. import shlex
  7. import subprocess
  8. __all__ = ['WindowsParser', 'PosixParser', 'NativeParser']
  9. class CommandLineParser:
  10. """
  11. An object that knows how to split and join command-line arguments.
  12. It must be true that ``argv == split(join(argv))`` for all ``argv``.
  13. The reverse neednt be true - `join(split(cmd))` may result in the addition
  14. or removal of unnecessary escaping.
  15. """
  16. @staticmethod
  17. def join(argv):
  18. """ Join a list of arguments into a command line string """
  19. raise NotImplementedError
  20. @staticmethod
  21. def split(cmd):
  22. """ Split a command line string into a list of arguments """
  23. raise NotImplementedError
  24. class WindowsParser:
  25. """
  26. The parsing behavior used by `subprocess.call("string")` on Windows, which
  27. matches the Microsoft C/C++ runtime.
  28. Note that this is _not_ the behavior of cmd.
  29. """
  30. @staticmethod
  31. def join(argv):
  32. # note that list2cmdline is specific to the windows syntax
  33. return subprocess.list2cmdline(argv)
  34. @staticmethod
  35. def split(cmd):
  36. import ctypes # guarded import for systems without ctypes
  37. try:
  38. ctypes.windll
  39. except AttributeError:
  40. raise NotImplementedError
  41. # Windows has special parsing rules for the executable (no quotes),
  42. # that we do not care about - insert a dummy element
  43. if not cmd:
  44. return []
  45. cmd = 'dummy ' + cmd
  46. CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
  47. CommandLineToArgvW.restype = ctypes.POINTER(ctypes.c_wchar_p)
  48. CommandLineToArgvW.argtypes = (ctypes.c_wchar_p, ctypes.POINTER(ctypes.c_int))
  49. nargs = ctypes.c_int()
  50. lpargs = CommandLineToArgvW(cmd, ctypes.byref(nargs))
  51. args = [lpargs[i] for i in range(nargs.value)]
  52. assert not ctypes.windll.kernel32.LocalFree(lpargs)
  53. # strip the element we inserted
  54. assert args[0] == "dummy"
  55. return args[1:]
  56. class PosixParser:
  57. """
  58. The parsing behavior used by `subprocess.call("string", shell=True)` on Posix.
  59. """
  60. @staticmethod
  61. def join(argv):
  62. return ' '.join(shlex.quote(arg) for arg in argv)
  63. @staticmethod
  64. def split(cmd):
  65. return shlex.split(cmd, posix=True)
  66. if os.name == 'nt':
  67. NativeParser = WindowsParser
  68. elif os.name == 'posix':
  69. NativeParser = PosixParser