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)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java为什么活动性/就绪性探测失败?   安卓上的java缩放图像   java如何切换一个类或改进它   java如何使用BouncyCastle lightwigth API生成cms封装数据   java如何构建pom。从github下载的maven项目中的xml?   java如何在允许扩展的同时,将具有不同字段计数的分隔文本行解析到对象中?   连接到网站jsoup项目中的java错误(类型jsoup的方法connect(字符串)未定义)   反射获取java。调用方法时发生lang.NullPointerException。援引   带有构造函数参数的java Spring自动关联依赖项   java Android:使用双数组时如何识别按钮?   java Maven无法获取可执行jar:无法加载主类   java SonarQube问题:重命名此常量名称以匹配正则表达式“^[AZ][AZ09]([AZ09]+)$”   java如何将Jbutton从另一个类添加到主类   java当我在排序后尝试在数组中插入值时,得到的默认值为0   java,try块在操作来自try作用域上方作用域的变量时产生错误   java如何用easy mock模拟消费者链接?