输入期间的Python动作()

时间:2018-01-09 01:32:59

标签: python python-3.x

这类似于here

我正在尝试在输入中为聊天系统做其他操作我正在使用套接字,但链接中的方法似乎不适用于python 3,这个< em>略修改后的代码:

import thread
import time

waiting = 'waiting'
i = 0

awesomespecialinput = None

def getinput():
    global var
    awesomespecialinput = input("what are you thinking about")

thread.start_new_thread(getinput,())


while awesomespecialinput == None:
    waiting += '.'
    print(waiting)
    i += 1
    time.sleep(1)

print('it took you',i,'seconds to answer')

输出:

Traceback (most recent call last):
  File "/home/pi/python/inputtest2.py", line 1, in <module>
    import thread
ImportError: No module named 'thread'

我对线程一无所知,但想对线程有一些有用的远见,如果有的话。

修改

更改了代码:

import threading
import time

waiting = 'waiting'
i = 0

awesomespecialinput = None

def getinput():
    global awesomespecialinput
    awesomespecialinput = input("what are you thinking about")

threading.start_new_thread(getinput,())


while awesomespecialinput == None:
    waiting += '.'
    print(waiting)
    i += 1
    time.sleep(1)

print('it took you',i,'seconds to answer')

输出:

AttributeError: module 'threading' has no attribute 'start_new_thread'

1 个答案:

答案 0 :(得分:1)

在Python 3中,您可以threading.Thread使用getinput函数作为target参数:

import threading
import time


waiting = 'waiting'
i = 0
awesomespecialinput = None

def getinput():
    global awesomespecialinput
    awesomespecialinput = input("what are you thinking about")

threading.Thread(target=getinput).start()

while awesomespecialinput is None:
    waiting += '.'
    print(waiting)
    i += 1
    time.sleep(1)

print('it took you', i, 'seconds to answer')

(您尝试使用的start_new_thread方法在Python 3&#39} threading模块中不可用,因为它是{{3 API。)