猛击巨蟒
bash的Python项目详细描述
一个库,可以在 Python
安装
使用pip安装:
pip install bash
用法
像在bash中一样运行命令:
>>> from bash import bash >>> bash('ls . | grep ".pyc"') bash.pyc tests.pyc
相同效果的链命令:
>>> bash('ls . ').bash('grep ".pyc"') bash.pyc tests.pyc
如果以后需要重用这样一个命令,这将变得越来越有用:
>>> b = bash('ls . ') >>> b.bash('grep ".pyc"') bash.pyc tests.pyc >>> b.bash('grep ".py$') bash.py tests.py
访问stdout和stderr属性:
>>> b = bash('ls tests.py') >>> b.stdout 'tests.py\n' >>> b.stderr ''
获取由命令生成的返回代码:
>>> b = bash('ls tests.py') >>> b tests.py >>> b.code 0
要获取bash.stdout call value()的精简Unicode字符串版本:
>>> b = bash('ls tests.py').value() u'tests.py'
动机
我发现我经常要写同样的代码来处理 从python运行bash命令。
这提供了一个pip可安装、经过测试的写入快捷方式:
from subprocess import PIPE, Popen p = Popen(cmd, shell=True, stdout=PIPE, stdin=PIPE, stderr=PIPE) output, err = p.communicate()
警告
请注意,这个库在hood下使用shell=True。这意味着 这个库not适合运行不受信任的命令。 (See explanation)
运行测试
只需使用测试运行程序
$ nosetests