2014-11-20 70 views
-4

如何在python中使用sh模块来完成this processPython sh:合并结果和管道

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

谢谢。

+0

因为您正在处理代码而不是图像,请在此处添加您的代码! – Kasramvd 2014-11-20 18:28:32

+0

@Kasra你是什么意思? unix代码在那里。当然,没有Python代码,因为我不知道如何编写它。 – bongbang 2014-11-20 20:20:06

+0

你知道如何使用'sh'模块吗?您是否遇到管道问题,或者{...}'构造,或者路径名称模式“〜/ folder/*”? – chepner 2014-11-21 19:10:10

回答

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) 

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 
+0

谢谢。所以'sh'模块不能完成这个,那么? – bongbang 2014-11-26 00:40:43

+0

@ bongbang。 TBH,我忽略了'sh'的要求,而我只是使用了标准库中的内容。我对“sh”一无所知,但我明天可能会看看它,如果能拿出任何东西,请更新我的答案。 – ekhumoro 2014-11-26 01:15:00

+0

@bongbang。我在我的答案中加了一个'sh'式的解决方案。 – ekhumoro 2014-11-26 21:05:19