python Fabric库学习
fabric官网
http://www.fabfile.org/
wrapper封装
v1.12
fabric是一个python库,同时也是一个命令行工具,其利用ssh进行应用开发或是系统管理任务。
它提供了一个基础的操作套件,可用来在本地亦或是远端执行shell命令,也可用来上传或是下载文件,同时也附带其他功能 such as prompting the running user for input, or aborting execution.
1、Overview and Tutorial
(1)它是能让你通过命令行来执行python函数的工具
(2)它是一个库帮助你通过ssh来执行shell命令
例如:
fabfile.py
def hello():
print("Hello world!")
$ fab hello
Hello world!
Done.
发生了什么:fab工具导入fabfile.py文件,然后执行函数。
对fabric的封装,把它的local接口封装成try_execute
使用fabric远程执行命令
import fabric.operations
fabric.operations.run(cmd)
_run_command()
_execute()
fabric local函数中使用了subprocess
local和run实现方式不一致。。。
local 的capture=True和False
也就是标准输出,标准错误输出,是直接打印出来还是捕获到变量中。
if capture:
out_stream = subprocess.PIPE
err_stream = subprocess.PIPE
else:
dev_null = open(os.devnull, 'w+')
# Non-captured, hidden streams are discarded.
out_stream = None if output.stdout else dev_null
err_stream = None if output.stderr else dev_null
try:
cmd_arg = wrapped_command if win32 else [wrapped_command]
p = subprocess.Popen(cmd_arg, shell=True, stdout=out_stream,
stderr=err_stream, executable=shell,
close_fds=(not win32))
(stdout, stderr) = p.communicate()
finally:
if dev_null is not None:
dev_null.close()
# Handle error condition (deal with stdout being None, too)
out = _AttributeString(stdout.strip() if stdout else "")
err = _AttributeString(stderr.strip() if stderr else "")
out.command = given_command
out.real_command = wrapped_command
out.failed = False
out.return_code = p.returncode
out.stderr = err
if p.returncode not in env.ok_ret_codes:
out.failed = True
msg = "local() encountered an error (return code %s) while executing '%s'" % (p.returncode, command)
error(message=msg, stdout=out, stderr=err)
out.succeeded = not out.failed
# If we were capturing, this will be a string; otherwise it will be None.
return out
子进程
subprocess.PIPE
p = subprocess.Popen(cmd , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.stdout.read()
communicate()
python中使用管道
subprocess.PIPE实际上为文本流提供一个缓存区。child1的stdout将文本输出到缓存区,随后child2的stdin从该PIPE中将文本读取走
child1 = subprocess.Popen([“cat”,”/etc/passwd”], stdout=subprocess.PIPE)
child2 = subprocess.Popen([“grep”,”0:0”],stdin=child1.stdout, stdout=subprocess.PIPE)
out = child2.communicate()