巨蟒的外壳力量。
shell.p的Python项目详细描述
将shell脚本的好部分引入python。
安装
$ pip install shell.py
用法
执行shell命令
阻塞直至返回:
>>>fromshellimportex>>>ex('echo hello shell.py').stdout()'hello shell.py\n'
异步执行:
>>>fromshellimportex>>>c=asex('echo hello shell.py')>>># do something else...>>>c.stdout()# wait until process exit and read stdout'hello shell.py\n'
管道命令
fromshellimportexre=(ex("ifconfig")|"grep -A 1 eth0"|"grep inet"|"awk '{print $2}'"|"cut -d: -f 2").stdout()
或
fromshellimportpipe_allpipe_all(["ls -la ~","awk '{print $9}'","grep -E '^\.'","wc -l"]).stdout()
使用字符串作为stdin
>>>fromshellimportinstream>>>instream("1 2 3").p("awk '{print $1}'").stdout()'1\n'
这相当于:
>>>fromshellimportex>>>ex("echo 1 2 3").p("awk '{print $1}'").stdout()
IO重定向
覆盖文件:
>>>fromshellimportex>>>ex('echo yolo').wr('/tmp/out')>>>ex('echo yolo')>'/tmp/out'
附加到文件:
>>>fromshellimportex>>>ex('echo yolo').ap('/tmp/out')>>>ex('echo yolo')>>'/tmp/out'
并行运行命令
阻止,直到所有命令返回:
>>>fromshellimportparallelaspar>>>par.ex_all(['sleep 2','sleep 2'])# return in 2s
异步并行执行:
>>>fromshellimportparallelaspar>>>pe=par.asex_all(['sleep 2','sleep 2'])# return immediately>>># do something else...>>>pe.wait()
设置工作目录
设置执行命令的目录:
>>>withshell.cwd('~/server/data/upload/')asold_path:>>>shell.ex('find ./images -name "*.png"')|'minify ./public'>>'upload.log'
这相当于:
>>>shell.ex('find ~/server/data/upload/images -name "*.png"')|'minify ~/server/data/upload/public'>>'~/server/data/upload.log'
有关更多示例,请参见测试用例。
测试
使用鼻测试(至少v1.3.0)运行测试:
$ make test