如何在python中使用sh模块来完成this process?Python sh:合并结果和管道
{ cat wordlist.txt ; ls ~/folder/* ; } | wc -l
谢谢。
如何在python中使用sh模块来完成this process?Python sh:合并结果和管道
{ cat wordlist.txt ; ls ~/folder/* ; } | wc -l
谢谢。
使用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)
UPDATE:
不知道这是否是做事情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
因为您正在处理代码而不是图像,请在此处添加您的代码! – Kasramvd 2014-11-20 18:28:32
@Kasra你是什么意思? unix代码在那里。当然,没有Python代码,因为我不知道如何编写它。 – bongbang 2014-11-20 20:20:06
你知道如何使用'sh'模块吗?您是否遇到管道问题,或者{...}'构造,或者路径名称模式“〜/ folder/*”? – chepner 2014-11-21 19:10:10