2014-11-20 24 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