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为什么加载个人密钥库需要这么多时间?   当我使用main创建Android应用程序UI时,如何通过java修改它。xml文件?   java Tomcat 6和7:WebappClassLoader:尝试为名称org/apache/openjpa/persistence/osgi/BundleUtils复制类定义   java`parseInt()`和`parseDouble()`throw`NumberFormatExeption`   JavaSpringMongoDB填充引用   在LinuxMint中打开Eclipse时发生java错误;OpenJDK 64位服务器VM警告:忽略选项MaxPermSize=512m;支持在8.0中被删除   使用PKCS7Padding的AES CBC加密在Java和Objective中有不同的结果   java为什么Jackson要用一个以类命名的额外层来包装我的对象?   json在Java中使用parallelStream提取值   JavaSpring存储库自动生成方法:按给定的顶部编号+按字段描述排序选择   java是否有可序列化的标准闭包接口?   .NET与Java在初创公司的web应用程序开发   如何修复java。java中的lang.unsatifiedLinkError   JavaFX+Spring Boot+Hibernate应用程序对多个环境的java支持   自定义视图组中的java更改未呈现