如何在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