Python sh:合并结果和管道

时间:2014-11-20 18:23:26

标签: python sh

如何使用sh模块在python中完成this process

{ cat wordlist.txt ; ls ~/folder/* ; } | wc -l

感谢。

1 个答案:

答案 0 :(得分:1)

使用subprocess和共享的pipe

>>> import os
>>> from subprocess import Popen, PIPE
>>> rfd, wfd = os.pipe()
>>> p1 = Popen(['cat', 'some/file'], stdout=wfd)
>>> p2 = Popen(['ls', 'some/path'], stdout=wfd)
>>> os.close(wfd)
>>> p3 = Popen(['wc', '-l'], stdin=rfd, stdout=PIPE)
>>> print(p3.communicate()[0].decode())
512

>>> os.close(rfd)

<强>更新

不确定这是否是使用sh执行操作的正确方法,但这似乎有效:

>>> import os, io, sh
>>> stream = io.BytesIO()
>>> sh.cat('some/file', _out=stream)
>>> sh.ls('some/folder', _out=stream)
>>> stream.seek(0)
>>> sh.wc('-l', _in=stream)
512