【发布时间】:2018-10-25 08:50:14
【问题描述】:
我正在尝试使用 python 的 subprocess 模块运行两个不同的命令并捕获它们的输出并将其打印到控制台...
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()
因此,当我分别运行这两种方法时,它们按预期工作,但是当我尝试并行运行它们然后打印两个输出时,似乎存在问题。 (请忽略缩进)
【问题讨论】:
-
target必须是可调用的。不要像target=run_command_XY()那样事先调用它。请改用target=run_command_XY。 -
@VikrantSharma 感谢您的回复。我试过这样做,但原来的问题仍然存在。 cmd 上只显示 XY_thread 的输出
-
您应该包含更多代码,以指示这两个函数的作用、其中的打印内容以及您的输出。
-
@VikrantSharma 更新了帖子,如果我做错了什么,请检查并告诉我。
-
你能修复缩进吗?这一切都不对劲了。并提供与您想要实现的目标类似的东西?一个最小的、可验证的、完整的例子。可能没有“某些命令”和“某些条件”。我开始认为问题可能不在于线程。
标签: python multithreading subprocess