crazicrafter1
crazicrafter1

Reputation: 323

Python Actions during an input()

This is similar to this here.

I am trying to do other actions during an input for a chat system i'm working on using sockets, but the method in the link doesnt seem work in python 3, with this slightly modified code:

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')

And output:

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

I have no knowledge about threads, but would like to have some useful foresight on threads, if anything.

EDIT

changed code:

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')

output:

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

Upvotes: 1

Views: 315

Answers (1)

Arminius
Arminius

Reputation: 2623

In Python 3 you can use threading.Thread with your getinput function as target parameter:

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')

(The start_new_thread method you're trying to use is not available in Python 3's threading module as that's a higher-level wrapper around the _thread API.)

Upvotes: 1

Related Questions