commands.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """Execute shell commands via os.popen() and return status, output.
  2. Interface summary:
  3. import commands
  4. outtext = commands.getoutput(cmd)
  5. (exitstatus, outtext) = commands.getstatusoutput(cmd)
  6. outtext = commands.getstatus(file) # returns output of "ls -ld file"
  7. A trailing newline is removed from the output string.
  8. Encapsulates the basic operation:
  9. pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
  10. text = pipe.read()
  11. sts = pipe.close()
  12. [Note: it would be nice to add functions to interpret the exit status.]
  13. """
  14. from warnings import warnpy3k
  15. warnpy3k("the commands module has been removed in Python 3.0; "
  16. "use the subprocess module instead", stacklevel=2)
  17. del warnpy3k
  18. __all__ = ["getstatusoutput","getoutput","getstatus"]
  19. # Module 'commands'
  20. #
  21. # Various tools for executing commands and looking at their output and status.
  22. #
  23. # NB This only works (and is only relevant) for UNIX.
  24. # Get 'ls -l' status for an object into a string
  25. #
  26. def getstatus(file):
  27. """Return output of "ls -ld <file>" in a string."""
  28. import warnings
  29. warnings.warn("commands.getstatus() is deprecated", DeprecationWarning, 2)
  30. return getoutput('ls -ld' + mkarg(file))
  31. # Get the output from a shell command into a string.
  32. # The exit status is ignored; a trailing newline is stripped.
  33. # Assume the command will work with '{ ... ; } 2>&1' around it..
  34. #
  35. def getoutput(cmd):
  36. """Return output (stdout or stderr) of executing cmd in a shell."""
  37. return getstatusoutput(cmd)[1]
  38. # Ditto but preserving the exit status.
  39. # Returns a pair (sts, output)
  40. #
  41. def getstatusoutput(cmd):
  42. """Return (status, output) of executing cmd in a shell."""
  43. import os
  44. pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
  45. text = pipe.read()
  46. sts = pipe.close()
  47. if sts is None: sts = 0
  48. if text[-1:] == '\n': text = text[:-1]
  49. return sts, text
  50. # Make command argument from directory and pathname (prefix space, add quotes).
  51. #
  52. def mk2arg(head, x):
  53. import os
  54. return mkarg(os.path.join(head, x))
  55. # Make a shell command argument from a string.
  56. # Return a string beginning with a space followed by a shell-quoted
  57. # version of the argument.
  58. # Two strategies: enclose in single quotes if it contains none;
  59. # otherwise, enclose in double quotes and prefix quotable characters
  60. # with backslash.
  61. #
  62. def mkarg(x):
  63. if '\'' not in x:
  64. return ' \'' + x + '\''
  65. s = ' "'
  66. for c in x:
  67. if c in '\\$"`':
  68. s = s + '\\'
  69. s = s + c
  70. s = s + '"'
  71. return s