封装subprocess来执行命令,subprocess执行命令,comand.py#!/
封装subprocess来执行命令,subprocess执行命令,comand.py#!/
comand.py
#!/usr/local/python/bin# coding=utf-8'''A simple interface to execute shell commands.These ideas are taken from fabric/operations.py.Examples 1: execute local command # import command # out = command.local('uname -r') # print out.stdout 2.6.32 # print out.stderr '' # print out.succeeded TrueExample 2: execute command in remote host through ssh # import command # out = command.remote('10.x.x.x', 'uname -r') # print out.stdout 2.6.32'''__author__ = 'tuantuan.lv <dangoakachan@foxmail.com>'import subprocess# Taken from web/utils.pyclass Storage(dict): """ A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`. >>> o = storage(a=1) >>> o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> o['a'] 2 >>> del o.a >>> o.a Traceback (most recent call last): ... AttributeError: 'a' """ def __getattr__(self, key): try: return self[key] except KeyError, k: raise AttributeError, k def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] except KeyError, k: raise AttributeError, k def __repr__(self): return '<Storage ' + dict.__repr__(self) + '>'def remote(ip, cmd, capture = True, timeout = None): ssh = "ssh -o StrictHostKeyChecking=no -o LogLevel=quiet -o BatchMode=yes" if timeout is not None: ssh += ' -o ConnectTimeout=%d' % timeout cmd = '%s %s "%s"' % (ssh, ip, cmd) return local(cmd, capture)def local(cmd, capture = True, shell = None): out_stream = subprocess.PIPE if capture else None err_stream = subprocess.PIPE if capture else None p = subprocess.Popen(cmd, shell = True, stdout = out_stream, stderr = err_stream, executable = shell) (stdout, stderr) = p.communicate() out = Storage() out.stdout = stdout.strip() if stdout else "" out.stderr = stderr.strip() if stdout else "" out.cmd = cmd out.failed = False out.return_code = p.returncode if p.returncode != 0: out.failed = True out.succeeded = not out.failed return out
相关内容
- Python的logging模块封装,pythonlogging模块,log.py#!/usr
- python获得本地计算机的名字,python获得计算机,import s
- Python 获取服务器信息,python获取服务器,sUrl = '<a h
- python 自动重启本程序,python重启程序,[Python]代码#!
- 仿内置用法 按key分组成嵌套字典,key嵌套,[Python]代码
- python 可分组字典 对象按属性分组成字典,python字典,
- 多线程找当前目录(包括子目录)占用空间前25位的文件,
- 列表去重,不打乱原来的顺序,列表打乱顺序,l两个方
- python 操作MYSQL,python操作mysql,sl.py#coding
- 正则 获取网页中的链接地址 并判断是否不是HTTP地址
评论关闭