python-sh
跳转到导航
跳转到搜索
sh 模块是相当方便的一个单文件进程操作库。
命令设置
要更改默认,可修改 sh.Command 的 _call_args 字典,如使命令输出默认不重定向:
sh.Command._call_args.update(out=sys.stdout, err=sys.stderr)
缓存
默认 stdin 不缓存,stdout 和 stderr 进行行缓存。因此使用交互函数输入密码时需要设置 _out_bufsize 为 0 ,同时要自行收集整理单个传入的字符。
tty
默认 stdin 为管道,stdout 为 tty。
重定向
指定 _out 关键字参数将指定命令输出的去向。参数可为 file-like 对象、文件名字符串或者交互函数。默认为 None ,将保存到命令结果的 .stdout 属性。指定 _no_out 为 True 则丢弃标准输出。
_err关键字参数与_out类似。
交互函数接受两个或者三个参数,依次是:进程输入字符串,标准输入( Queue 对象),进程对象自身。使用交互函数时,需要手工调用 wait() 方法。示例如下:
def answerwith(prompt, which):
line = ''
def _answersudo(ch, stdin):
nonlocal line
sys.stdout.write(ch) # or it'll be lost
line += ch
if line.startswith(prompt):
stdin.put(getpassword(which) + '\n')
return _answersudo
answersudo = answerwith('[sudo] password for ', 'login')
sh.ssh('-t', host, cmdline, _tty_in=True, _out=answersudo, _out_bufsize=0).wait()