跳转到主要内容

轻量级管道子进程工具

项目描述

Vorlauf

是什么?

Vorlauf是一个非常小巧的工具,可以帮助你创建进程管道(在shell意义上)。它还帮助分离出进程的定义和运行该进程的过程,包括给定的stdin、stdout和stderr。

为什么?

因为链式连接进程的subprocess API很繁琐,而且文档也不太完善。

怎么做?

这个库基本上什么也不做——它的实现不到100行。有两个类可用,分别是ProcessPipeline

Process

Process类接收args、cwd和env参数,并通过调用带有可选的stdin、stdout和stderr参数的Process.run方法来执行。

通过从Process类的创建中移除stdout、stderr和stdin,我们可以创建可重用的Process定义

critical_grepper = Process('grep', 'CRITICAL')

syslog = open('/var/log/syslog', 'r')
apachelog = open('/var/log/httpd/error.log', 'r')

filtered = open('critical.log', 'w')

for logfile in (syslog, apachelog):
  critical_grepper.run(stdin=logfile, stdout=filtered)

Pipeline

Pipeline类存储了一个Process类的列表,这些类在用Pipeline.run方法(可选的stdin和stdout)运行时,会将进程连接起来。如果有,stdin将被传递给第一个进程,如果有,stdout将被传递给最后一个进程。

示例

from vorlauf import Pipeline, Process

pipeline = Pipeline()
pipeline.add(Process('cat', 'foo.txt'))
pipeline.add(Process('grep', 'something'))
pipeline.add(Process('uniq'))

with open('new.txt', 'wb') as fd:
    pipeline.run(stdout=fd)

由于Process和Pipeline类内置了操作符重载,这可以简化为

from vorlauf import Process as P

pipeline = P('cat', 'foo.txt') | P('grep', 'something') | P('uniq')
with open('new.txt', 'wb') as fd:
    pipeline.run(stdout=fd)

最后,您可以使用Process类创建可重用组件

from vorlauf import Process

class GPG(Process):

    def __init__(self, passphrase):
        super(GPG, self).__init__('gpg', '-c', '--passphrase', passphrase, '-')


class MySQLDump(Process):

    def __init__(self, password, dbname, **kwargs):
        super(MySQLDump, self).__init__(
            'mysqldump', '-u', 'root', '-p{}'.format(password), dbname
        )


with open('mysql.dump', 'wb') as fd:
    pipeline = MySQLDump('loldongs', 'foo') | GPG('supersekrit')
    pipeline.run(stdout=fd)

测试

运行

virtualenv venv
venv/bin/pip install -e .
venv/bin/python test.py

更新日志

1.0.0 (2015-09-22)

  • 初始版本

项目详情


下载文件

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

源代码发行版

vorlauf-1.0.0.tar.gz (3.2 kB 查看哈希值)

上传时间 源代码

由以下提供支持