![](/img/trans.png)
[英]Is there a way to both stream and capture output from subprocess.run in Python 3?
[英]Runs two different commands from subprocess and capture the output of both the process Python
我正在嘗試使用python的子進程模塊運行兩個不同的命令並捕獲它們的輸出並將其打印到控制台...
XY_thread =線程(目標= run_command_XY)
TEXT_thread =線程(目標= run_command_text)
XY_thread.start()
TEXT_thread.start()
因此,我從XY_thread而不是TEXT_thread獲得輸出。 當我互換線程並首先啟動TEXT_thread時,僅顯示TEXT_thread輸出。
我被打到這里了,請幫忙。 我在這里想念什么嗎?
import subprocess
from subprocess import Popen, PIPE
from threading import Thread
def run_command_text():
command = "SOME COMMAND"
process_ = Popen(command.split(), stdout = PIPE, shell = False)
prev_line = None
retcode = process_.poll()
while(process_.poll() == None):
line_ = process_.stdout.readline().decode('utf-8')
if "SOME CONDITION" in line_:
# does some operation and fetches the text(no issues with this part)
if text != "":
print(text)
prev_line = line_
if retcode is not None:
break
def run_command_XY():
command = "SOME COMMAND"
process = Popen(command.split(), stdout = PIPE, shell = False)
retcode = process.poll()
while(process.poll() == None):
line = process.stdout.readline().decode('utf-8')
# does some operation and fetches the X and Y(no issues with this part)
print(X+" "+Y)
if retcode is not None:
break
if __name__ == '__main__':
# multiprocessor = list()
XY_thread = Thread(target = run_command_XY)
TEXT_thread = Thread(target = run_command_text)
XY_thread.start()
TEXT_thread.start()
因此,當我分別運行這兩種方法時,它們按預期方式工作,但是當我嘗試並行運行它們,然后打印兩個輸出時,似乎出現了問題。 (請忽略縮進)
我試圖提供一個運行兩個線程並在每個線程中檢查進程輸出的小示例。 兩者目前都在做完全相同的事情,但這應該可以給您一個想法。
import subprocess as sp
from threading import Thread
def func_x():
cmd = 'python --version'
for _ in range(5):
proc = sp.Popen(cmd.split(), stdout=sp.PIPE)
proc.wait()
result = proc.stdout.read()
print('func_x:', result.decode('utf-8').strip())
def func_y():
cmd = 'python --version'
for _ in range(5):
proc = sp.Popen(cmd.split(), stdout=sp.PIPE)
proc.wait()
result = proc.stdout.read()
print('func_y:', result.decode('utf-8').strip())
if __name__ == '__main__':
x_thread = Thread(target=func_x)
y_thread = Thread(target=func_y)
x_thread.start()
y_thread.start()
哪個輸出:
func_y: Python 3.5.2
func_x: Python 3.5.2
func_y: Python 3.5.2
func_x: Python 3.5.2
func_y: Python 3.5.2
func_x: Python 3.5.2
func_x: Python 3.5.2
func_y: Python 3.5.2
func_y: Python 3.5.2
func_x: Python 3.5.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.