跳转到主要内容

Pythonic命令运行器

项目描述

CommandLib是subprocess的Pythonic包装器,允许您传递命令对象并级联

  • 参数

  • 路径

  • 其他环境变量

  • 运行时目录

  • 其他运行时属性(在shell中运行,隐藏stdout/stderr,忽略错误代码等)

它在某种程度上受到amoffat的sh、Kenneth Reitz的requests、jaraco的path.py和SQLAlchemy的启发。

要安装

$ pip install commandlib

示例

>>> from commandlib import Command
>>> ls = Command("ls")
>>> ls("-t").in_dir("/").with_shell().run()
sys  tmp  run  dev  proc  etc  boot  sbin  root  vmlinuz  initrd.img  bin  lib  opt  vmlinuz.old  initrd.img.old  media  home  cdrom  lost+found  var  srv  usr  mnt

CommandPath示例

>>> from commandlib import CommandPath
>>> bin = CommandPath("/bin")
>>> bin.ls("-t").in_dir("/").run()
sys  tmp  run  dev  proc  etc  boot  sbin  root  vmlinuz  initrd.img  bin  lib  opt  vmlinuz.old  initrd.img.old  media  home  cdrom  lost+found  var  srv  usr  mnt

API

>>> from commandlib import Command, 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做类似的事情,但有很多魔法(例如覆盖导入)。

  • envoy和sarge更专注于链式命令,而不是参数、环境变量等。

高级API

添加尾部参数

>>> from commandlib import Command, 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" inside projectdir ]

从包含可执行文件的目录中动态生成命令包

>>> from commandlib import CommandPath, Command, run
>>> postgres94 = CommandPath("/usr/lib/postgresql/9.4/bin/")
>>> run(postgres94.postgres)
[ Runs postgres ]

>>> run(postgres94.createdb)
[ Runs createdb ]

与path.py(或任何其他str(object)解析为字符串的库)一起使用

>>> from path import Path
>>> postgres94 = CommandPath(Path("/usr/lib/postgresql/9.4/bin/"))
>>> run(postgres94.postgres)

项目详情


下载文件

下载适合您平台的文件。如果您不确定该选择哪个,请了解有关安装包的更多信息。

源分发

commandlib-0.3.5.tar.gz (6.9 kB 查看哈希值)

上传时间