subprocess_fix.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # subprocess - Subprocesses with accessible I/O streams
  2. #
  3. # For more information about this module, see PEP 324.
  4. #
  5. # This module should remain compatible with Python 2.2, see PEP 291.
  6. #
  7. # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
  8. #
  9. # Licensed to PSF under a Contributor Agreement.
  10. # See http://www.python.org/2.4/license for licensing details.
  11. def list2cmdline(seq):
  12. """
  13. Translate a sequence of arguments into a command line
  14. string, using the same rules as the MS C runtime:
  15. 1) Arguments are delimited by white space, which is either a
  16. space or a tab.
  17. 2) A string surrounded by double quotation marks is
  18. interpreted as a single argument, regardless of white space
  19. contained within. A quoted string can be embedded in an
  20. argument.
  21. 3) A double quotation mark preceded by a backslash is
  22. interpreted as a literal double quotation mark.
  23. 4) Backslashes are interpreted literally, unless they
  24. immediately precede a double quotation mark.
  25. 5) If backslashes immediately precede a double quotation mark,
  26. every pair of backslashes is interpreted as a literal
  27. backslash. If the number of backslashes is odd, the last
  28. backslash escapes the next double quotation mark as
  29. described in rule 3.
  30. """
  31. # See
  32. # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
  33. result = []
  34. needquote = False
  35. for arg in seq:
  36. bs_buf = []
  37. # Add a space to separate this argument from the others
  38. if result:
  39. result.append(' ')
  40. needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or arg == ""
  41. if needquote:
  42. result.append('"')
  43. for c in arg:
  44. if c == '\\':
  45. # Don't know if we need to double yet.
  46. bs_buf.append(c)
  47. elif c == '"':
  48. # Double backspaces.
  49. result.append('\\' * len(bs_buf)*2)
  50. bs_buf = []
  51. result.append('\\"')
  52. else:
  53. # Normal char
  54. if bs_buf:
  55. result.extend(bs_buf)
  56. bs_buf = []
  57. result.append(c)
  58. # Add remaining backspaces, if any.
  59. if bs_buf:
  60. result.extend(bs_buf)
  61. if needquote:
  62. result.extend(bs_buf)
  63. result.append('"')
  64. return ''.join(result)