[英]How do I make my code do things in the background
在等待輸入時,如何確保我的代碼在做其他事情? 例如..
假設我要在輸入時計數到10,這當然沒用,但是我有理由學習...
test = 0
while test < 11:
test += 1
print test
raw_input("taking input")
顯然,每次都會停止輸入。 當用戶進行輸入時,如何使它計數?
如果您只需要在用戶輸入輸入時可以計數的內容,則可以使用線程:
from threading import Thread,Event
from time import sleep
class Counter(Thread):
def __init__(self):
Thread.__init__(self)
self.count = 0
self._stop = Event()
def run(self):
while not self._stop.is_set():
sleep(1)
self.count+=1
def stop(self):
self._stop.set()
count = Counter()
# here we create a thread that counts from 0 to infinity(ish)
count.start()
# raw_input is blocking, so this will halt the main thread until the user presses enter
raw_input("taking input")
# stop and read the counter
count.stop()
print "User took %d seconds to enter input"%count.count
如果您要在n
秒后停止raw_input
如果用戶未輸入任何輸入),那么這會稍微復雜一些。 最直接的方法可能是使用select
(盡管如果您在Windows計算機上,則不是)。 有關示例,請參見:
和
http://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/
您可能要使用線程。 這是一個非常簡單的示例:
#!/usr/bin/python
import time,readline,thread,sys
def counterThread():
t = 0
while True:
t += 1
if t % 50000000 == 0:
print "now"
thread.start_new_thread(counterThread, ())
while True:
s = raw_input('> ')
print s
在此示例中,程序開始計數,現在每打印50000000個循環。 在此期間,您可以輸入字符,緊隨其后顯示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.