我有以下代碼似乎可以工作,用於在逐行讀取/寫入(不使用communicate()
預先使用communicate()
)的同時將子系統中的管道與python鏈接在一起。該代碼只是調用UNIX命令(mycmd
),讀取其輸出,然後寫道,到另一個Unix命令(next_cmd
)的標準輸入,而且最後一個命令的輸出重定向到一個文件中。逐行鏈接在Python中使用子流程編寫/讀取管道
# some unix command that uses a pipe: command "a"
# writes to stdout and "b" reads it and writes to stdout
mycmd = "a | b"
mycmd_proc = subprocess.Popen(mycmd, shell=True,
stdin=sys.stdin,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# nextCmd reads from stdin, and I'm passing it mycmd's output
next_cmd = "nextCmd -stdin"
output_file = open(output_filename, "w")
next_proc = subprocess.Popen(next_cmd, shell=True,
stdin=subprocess.PIPE,
stdout=output_file)
for line in iter(mycmd.stdout.readline, ''):
# do something with line
# ...
# write it to next command
next_proc.stdin.write(line)
### If I wanted to call another command here that passes next_proc output
### line by line to another command, would I need
### to call next_proc.communicate() first?
next_proc.communicate()
output_file.close()
這似乎工作,它只能在命令的末尾調用communicate()
。
我想擴展這個代碼再添加一個命令,所以你可以做:
mycmd1 | mycmd2 | mycmd3 > some_file
含義:一行行,用Python讀mycmd1的輸出,過程線,將其提供給mycmd2,讀mycmd2的輸出和逐行過程中它和飼料它mycmd3這又使其輸出在some_file
。這是可能的還是這種綁定在死鎖/阻塞/不刷新的緩衝區?請注意,我不只是將三個unix命令作爲管道調用,因爲我想在它們之間插入Python,並在將每個命令的輸出逐行後送到下一個命令之前逐行進行處理。
我想避免調用溝通和加載所有的輸出到內存中 - 而不是我要一行行解析它。謝謝。
你看這個例子在手冊中? http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline – zigg 2013-03-03 20:34:18
@zigg:肯定,但它並沒有回答這個問題。我不只是製作一個管道,我想從一個管道讀取數據並寫入另一個管道,而不是隻調用發生在管道上的unix命令。對於我來說,瞭解在讀/寫塊或在什麼時候可以發生緩衝區是非常重要的。 – user248237dfsf 2013-03-03 20:42:44
我的歉意;你是對的。我應該更仔細地閱讀你的問題。 – zigg 2013-03-03 22:50:26