[关闭]
@bergus 2015-12-11T02:33:50.000000Z 字数 1374 阅读 1994

pyshell

pyshell python shell


pyshell 调用外部命令,让你像执行bash一样方便

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. from subprocess import Popen
  4. from subprocess import PIPE
  5. def py_ver():
  6. '''
  7. 得到python的版本
  8. '''
  9. import sys
  10. return sys.version_info[0]
  11. _ver = py_ver()
  12. if _ver == 2:
  13. builtin_str = str
  14. bytes = str
  15. str = unicode
  16. basestring = basestring
  17. numeric_types = (int, long, float)
  18. elif _ver == 3:
  19. builtin_str = str
  20. str = str
  21. bytes = bytes
  22. basestring = (str, bytes)
  23. numeric_types = (int, float)
  24. else:
  25. raise ValueError(u'python 版本不正确')
  26. del _ver
  27. # 解析字符串中的环境变量
  28. def parse_shell_token(t):
  29. import os
  30. # 将~等用用户的家目录进行替换
  31. t = os.path.expanduser(t)
  32. # path中可以使用环境变量,'$PATH'...
  33. t = os.path.expandvars(t)
  34. return t
  35. class cmd(object):
  36. def __init__(self, *args, **kwargs):
  37. self.stdout = None
  38. self.cmd(*args, **kwargs)
  39. def cmd(self, cmd, env=None, stdout=PIPE):
  40. p = Popen(parse_shell_token(cmd), shell=True,
  41. stdout=stdout, stdin=PIPE, stderr=PIPE, env=env)
  42. self.stdout, self.stderr = p.communicate(input=self.stdout)
  43. self.code = p.returncode
  44. return self
  45. def __repr__(self):
  46. return self.value()
  47. def __unicode__(self):
  48. return self.value()
  49. def __str__(self):
  50. return self.value()
  51. def __nonzero__(self):
  52. return self.__bool__()
  53. def __bool__(self):
  54. return bool(self.value())
  55. def value(self):
  56. if not self.stdout:
  57. return ''
  58. return self.stdout.strip()
  59. if __name__ == '__main__':
  60. print cmd('ls -al')
  61. print cmd("ls | grep 'LICENSE'")
  62. print cmd("konsole --hold -e 'konsole --help'")
  63. print cmd('ls $HOME')
  64. print cmd('ls ~')
  65. dd = cmd('ls ~').value().split('\n')
  66. print dd
  67. cmd("gnome-terminal -x bash -c 'python -h;read' ")
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注