Python:raw_input并在线程中打印 [英] Python : raw_input and print in a thread

查看:78
本文介绍了Python:raw_input并在线程中打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以在控制台上打印一些文本的线程,主程序有一个raw_input来控制该线程.

I have a thread which can print some text on the console and the main program have a raw_input to control the thread.

我的问题是当我在写线程的时候,我也得到了这样的东西:

My problem is when I'm writing and the thread too I get something like this:

-->whatiwWHATTHETHREADWRITErite

但是我想得到这样的东西

but I would like to get some thing like this

WHATTHETHREADWRITE
-->whatiwrite

谢谢!

推荐答案

您必须将输入与线程输出同步,以防止它们同时发生.

You have to syncronize your input with the thread output preventing them from happening at the same time.

您可以像这样修改主循环:

You can modify the main loop like:

lock = threading.lock()

while 1:
    raw_input()     # Waiting for you to press Enter
    with lock:
        r = raw_input('--> ')
        # send your command to the thread

然后锁定后台线程打印:

And then lock the background thread printing:

def worker(lock, ...):
    [...]
    with lock:
        print('what the thread write')

简而言之,当您Press Enter时,将停止线程并进入输入模式".

In short when you Press Enter you will stop the thread and enter in "input mode".

更具体地说,每次您Press Enter您都会:

To be more specific, every time you Press Enter you will:

  • 等待锁可用
  • 获取锁
  • 打印-->并等待您的命令
  • 插入命令
  • 将该命令发送到线程
  • 释放锁
  • wait for the lock to be available
  • acquire the lock
  • print --> and wait for your command
  • insert your command
  • send that command to the thread
  • release the lock

因此,只有当您处于输入模式"时,线程尝试打印时,线程才会停止
在您的终端中,您将得到类似的信息:

So your thread will be stopped only if it tries to print when you are in "input mode",
and in your terminal you'll get something like:

some previous output

---> your input
THE THREAD OUTPUT

这篇关于Python:raw_input并在线程中打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆