Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. __all__ = ["getstatusoutput","getoutput","getstatus"]
  15. # Module 'commands'
  16. #
  17. # Various tools for executing commands and looking at their output and status.
  18. #
  19. # NB This only works (and is only relevant) for UNIX.
  20. # Get 'ls -l' status for an object into a string
  21. #
  22. def getstatus(file):
  23. """Return output of "ls -ld <file>" in a string."""
  24. return getoutput('ls -ld' + mkarg(file))
  25. # Get the output from a shell command into a string.
  26. # The exit status is ignored; a trailing newline is stripped.
  27. # Assume the command will work with '{ ... ; } 2>&1' around it..
  28. #
  29. def getoutput(cmd):
  30. """Return output (stdout or stderr) of executing cmd in a shell."""
  31. return getstatusoutput(cmd)[1]
  32. # Ditto but preserving the exit status.
  33. # Returns a pair (sts, output)
  34. #
  35. def getstatusoutput(cmd):
  36. """Return (status, output) of executing cmd in a shell."""
  37. import os
  38. pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
  39. text = pipe.read()
  40. sts = pipe.close()
  41. if sts is None: sts = 0
  42. if text[-1:] == '\n': text = text[:-1]
  43. return sts, text
  44. # Make command argument from directory and pathname (prefix space, add quotes).
  45. #
  46. def mk2arg(head, x):
  47. import os
  48. return mkarg(os.path.join(head, x))
  49. # Make a shell command argument from a string.
  50. # Return a string beginning with a space followed by a shell-quoted
  51. # version of the argument.
  52. # Two strategies: enclose in single quotes if it contains none;
  53. # otherwise, enclose in double quotes and prefix quotable characters
  54. # with backslash.
  55. #
  56. def mkarg(x):
  57. if '\'' not in x:
  58. return ' \'' + x + '\''
  59. s = ' "'
  60. for c in x:
  61. if c in '\\$"`':
  62. s = s + '\\'
  63. s = s + c
  64. s = s + '"'
  65. return s