pythonic命令行程序
commandlib的Python项目详细描述
commandlib是一个pythonic包装子流程,允许您传递命令对象。 菊花链:
- 参数
- 路径
- 其他环境变量
- 运行时目录
- 其他运行时属性(在shell中运行、隐藏stdout/stderr、忽略错误代码等)
它的灵感来自于阿莫法特的sh、肯尼斯·雷茨的请求、jaraco的path.py。 和炼金术。
要安装:
$ pip install commandlib
示例:
>>>fromcommandlibimportCommand>>>ls=Command("ls")>>>ls("-t").in_dir("/").with_shell().run()systmprundevprocetcbootsbinrootvmlinuzinitrd.imgbinliboptvmlinuz.oldinitrd.img.oldmediahomecdromlost+foundvarsrvusrmnt
命令路径示例:
>>>fromcommandlibimportCommandPath>>>bin=CommandPath("/bin")>>>bin.ls("-t").in_dir("/").run()systmprundevprocetcbootsbinrootvmlinuzinitrd.imgbinliboptvmlinuz.oldinitrd.img.oldmediahomecdromlost+foundvarsrvusrmnt
API
>>>fromcommandlibimportCommand,run# Create command object>>>py=Command("/usr/bin/python")# Run with *additional* environment variable PYTHONPATH (*added* to global environment when command is run)>>>py=py.with_env(PYTHONPATH="/home/user/pythondirectory")# Run with additional path (appended to existing PATH environment variable when command is run)>>>py=py.with_path("/home/user/bin")# Run in specified directory (default is current directory)>>>py=py.in_dir("/home/user/mydir")# Run in shell>>>py=py.with_shell()# Suppress stderr>>>py=py.silently()# Suppress stdout and stderr# Finally run command explicitly with all of the above>>>run(py)>>>py.run()# alternative syntax
为什么?
commandlib是一个库,它使在不同的 模块和类,并以可读的方式增量修改命令的行为-添加环境 变量、路径等
- call、check_call和popen没有最友好的api,大量使用它们的代码会很快变得难看。
- sh也做了类似的事情,但是有很多魔力(例如,重写导入)。
- 特使和中士更专注于链接命令,而不是参数、环境变量等。
高级API
添加尾部参数:
>>>fromcommandlibimportCommand,run>>>manage=Command("/usr/bin/python","manage.py").with_trailing_arguments("--settings","local_settings.py").in_dir("projectdir")>>>run(manage("runserver"))[Runs"/usr/bin/python manage.py runserver --settings local_settings.py"insideprojectdir]
从包含可执行文件的目录动态生成命令包:
>>>fromcommandlibimportCommandPath,Command,run>>>postgres94=CommandPath("/usr/lib/postgresql/9.4/bin/")>>>run(postgres94.postgres)[Runspostgres]>>>run(postgres94.createdb)[Runscreatedb]
与path.py(或str(object)解析为字符串的任何其他库一起使用:
>>>frompathimportPath>>>postgres94=CommandPath(Path("/usr/lib/postgresql/9.4/bin/"))>>>run(postgres94.postgres)