python的shell脚本库
pyscripting的Python项目详细描述
pyscripting是一个python模块,它提供了各种工具来生成shell 使用python编写脚本更容易。
开始
获取scripting.py:
pip install pyscripting
创建python shell脚本myscript.py:
#!/usr/bin/env python from scripting import sh sh.ls('-l')
使用脚本:
chmod +x myscript.py ./myscript.py
调用外部命令
有三种方法可以调用外部命令。
如果可能,将使用python替换外部命令。 替换不能只在直接调用中使用。
有关所有替换的命令,请参见Replaced commands。
直接呼叫
返回退出代码。
sh('ls', '-l')
间接呼叫
返回退出代码。
sh.ls('-l')
调用并返回输出
返回剥离的stdout(不包括stderr)。
使用此方法,命令的输出将不会打印到stdout。以前 返回输出,前导空格将被删除。
不要将这种方法用于大输出。
output = sh.get('ls', '-l') print('Output was: %s' % output)
参数处理
您可以使用argv属性访问传递给脚本的参数:
sh.argv[0] - called script name sh.argv[1] - first argument
替换了命令
为了避免开销和简单起见,一些外部命令 替换为python的内部函数(工作速度更快),调用 外部命令。
- basename
与外部{tt5}$相同。
返回字符串。
- exit
- 与外部{tt7}$相同。
- find
类似于外部{tt9}$命令。
返回找到的所有文件的迭代器。
示例用法:
for f in sh.find(type='f', exclude=['*.pyc']): print(f)
- mkdir
- 与外部相同{tt11}$.
- mkdirs
- 与外部相同{tt14}$.
- test
类似于外部{tt15}$。
返回布尔值。
示例用法:
if sh.test('-d', '/tmp'): print('/tmp is directory.')
生成文件功能
示例(myscript.py):
#!/usr/bin/env python from scripting import sh, Makefile make = Makefile(sh) @make('/tmp/myfile.txt') def myrule(target): sh.touch(target) @make() def main(target): myrule() make.run(main)
最后一行make.run(main)检查sys.argv并执行指定的规则或 如果未指定特定规则,则为默认值。myrule将只执行, 如果目标文件^ {TT21}$不存在。
./myscript.py
现在调用特定规则:
./myscript.py myrule