2016-12-06 131 views
1

我在學習python以獲得樂趣,並且我正在嘗試實現的是一個程序,該程序不斷要求用戶通過While True循環輸入,同時仍在背景上運行其他腳本(由用戶選擇)Python:在進行用戶輸入時運行線程

我目前的工作正常......但並不完全如我所願。它需要用戶的輸入並像問題一樣啓動線程,但在等待用戶的下一個輸入時暫停它們。然後,它會打印我的線程應該每秒打印一次,但只有一次,在控制檯的下一次打印後打印。

我正在使用IDLE定期測試我的代碼,也許這可能有所幫助。

主要腳本

from mythreadclass import MyThread 

while True: 
    user_input = input("What do I do ? ") 

    if user_input == "start thread": 
     #Will start a threat that prints foo every second. 
     mythread = MyThread() 
     mythread.start() 

    elif user_input == "hello": 
     print("Hello !") 

    else: 
     print("This is not a correct command.") 

Thread類

import time 
from threading import Thread, Timer 

class MyThread(Thread): 
    def __init__(self): 
     Thread.__init__(self) 

    def run(self): 
     print("Thread started !") 
     while True: 
      self.foo() 
      time.sleep(1) 

    def foo(self): 
     print("foo !") 

執行時我有什麼:

What do I do ? 
>>> start thread 
Thread started ! 
What do I do ? 
>>> hello 
foo !Hello ! 
>>> hello 
foo !Hello ! 

正如你所看到的,線程應該每秒打印foo!,同時仍然要求用戶輸入下一個輸入。相反,它僅在用戶鍵入內容時才啓動線程並打印foo !:輸入暫停/阻塞線程。

我不知道,如果我想要實現的是清楚,所以這裏是

What do I do ? 
>>> start thread 
Thread started ! 
What do I do ? 
foo ! 
foo ! 
foo ! 
#User waited 3 seconds before typing hello so there should be 3 foos 
>>> hello 
Hello ! 
What do I do ? 
foo ! 
foo ! 

etc etc. 
+0

我改變'input'到'raw_input',它似乎都按預期工作。我把所有內容放在一個文件中。 – sal

+0

你在這裏寫的方式在python 3.5中完全適合我。這正是你寫的或者是一個例子嗎? –

+0

@JustinBell這是一個_(非常)_簡化的例子,但是我的整個項目在全局上是一樣的(在另一個文件中拋出線程的主類) – sohomangue

回答

-1

你做的線程錯誤。而不是無限遞歸,run()方法必須是這樣一個無限循環:

from threading import Thread 
import time 

class MyThread(Thread): 
    def __init__(self): 
     Thread.__init__(self) 
     self.start() 

    def run(self): 
     while (True): 
      self.foo() 
      time.sleep(1) 

    def foo(self): 
     print("foo !") 

my = None 

while True: 
    user_input = raw_input("What do I do ? ") 

    if user_input == "start thread": 
     #Will start a threat that prints foo every second. 
     if my == None: 
      print("Starting thread...") 
      my = MyThread() 
     else: 
      print("Thread is already started.") 

    elif user_input == "hello": 
     print("Hello !") 

    else: 
     print("This is not a correct command.") 
+0

這可能是真的,無限遞歸最終會導致一個問題(堆棧溢出,足夠方便:P),但我不認爲這是直接的問題@sohomangue面臨 –

+0

我不知道使用定時器無限是錯誤的,我我會解決這個問題!但是,使用'time.sleep()'不會改變輸出,程序仍然等待下一個控制檯打印輸出「foo!」而不是每秒打印一次。 – sohomangue

+0

我修改了我的代碼,使它對我來說就像你想要的那樣。 – Organis