子流程的类shell dsl前端。popen
popen的Python项目详细描述
波本
是什么?
popen包在python中为运行 外部命令。
功能:
- 锁链(又名管道)作为Sh('ls') | 'sort'
- 将stderr重定向到stdout asSh('make').include_stderr | 'wc'
- 将输出重定向到文件Sh('ls') > '~/listing.txt'
- 在输出行上迭代为for line in Sh('ls'):
- 将输入作为Sh.pipe('~/listing.txt').Sh('grep','-q','code').returncode 流式处理到链中的命令中
- 展开特殊字符(~*!?)
- 将env vars($HOME)扩展为print Sh('ls', '$USER', '~/*')
- 正确拆分字符串('echo "hole in one"'变成['echo', 'hole in one'])
- 或iterable参数(Sh('ls','-l') | ['wc', '-l'] > '/dev/null')
tl;dr
安装:
pip install popen
示例:
frompopenimportShforlineinSh('du','~/')|'head -n 10'|'sort -n':print('GOT',line)
用法
简化用法,运行命令并迭代输出行:
frompopenimportShforlineinSh('ls','-la','~'):printline
输出到文件的管道:
Sh('ls','-la','~')>'~/listing'
注意像~这样的特殊字符被扩展,环境也是 变量(例如$HOME)。
链接命令很简单,这里使用append而不是write to file:
Sh('ls')|Sh('sort')>>'~/listing'<^ >但是{tt15}$的右手边可以非常灵活,因为它使用 字符串输入上的分词器,或采用迭代:
Sh('ls','-la','~')|'sort -c'|['uniq','-c']|'tail'|Sh('wc')>'~/listing'
要运行命令并让输出转到stdout,请要求返回代码:
cmd=Sh('ls')|'grep polka'printcmd.returncode
要将字符串管道化为命令,请使用iterable:
printSh.pipe(['this is a \nmulti line\nstring.'])|'wc'