2

I am new to Python and am having trouble with this piece of code:

while true:
   rand = random.choice(number)
   print(rand)             
   enter_word = input("Write something: ")
   time.sleep(5)

I want to be able to input words in the console while, at the same time, have random numbers appear in the console. But a new number only appears once I input a word. What is the best way to make both these commands run at the same time?

Do I need to make a thread or is there something simpler I can do? And if I need to make a thread can you please give a little help on how I would create it?

Thanks in advance

user2456977
  • 3,830
  • 14
  • 48
  • 87
  • Have you considered creating a GUI: a text field for the input and a text area for the output? – jfs Sep 08 '14 at 23:45
  • I am eventually going to create a GUI. But would this fix my problem? – user2456977 Sep 09 '14 at 00:25
  • 1
    GUI usually uses an event loop that makes it simple to do things concurrently e.g., call repeatedly a function that populates the text area with random numbers while the text fields waits for input. – jfs Sep 09 '14 at 00:51
  • Thanks! so is Tkinter the best gui to use? I've also seen there's Jython and wxPython. – user2456977 Sep 09 '14 at 00:55
  • A minimal change to your code could be [`call_repeatedly(5, random.choice, number)`](http://stackoverflow.com/a/22498708/4279). Here's how to [repeat calls using Tkinter](http://stackoverflow.com/a/14040516/4279) – jfs Sep 09 '14 at 00:59

4 Answers4

3

This can be achieved by using the multiprocessing module in python, please find the code below

#!/usr/bin/python
from multiprocessing import Process,Queue
import random
import time

def printrand():
   #Checks whether Queue is empty and runs
   while q.empty():
      rand = random.choice(range(1,100))
      time.sleep(1)
      print rand


if __name__ == "__main__":
   #Queue is a data structure used to communicate between process 
   q = Queue()
   #creating the process
   p = Process(target=printrand)
   #starting the process
   p.start()
   while True:
      ip = raw_input("Write something: ")
      #if user enters stop the while loop breaks
      if ip=="stop":
         #Populating the queue so that printramd can read and quit the loop
         q.put(ip)
         break
   #Block the calling thread until the process whose join() 
   #method is called terminates or until the optional timeout occurs.
   p.join()
Ram
  • 1,115
  • 8
  • 20
  • You don't need a separate *process* to print numbers and wait for input in parallel. You could use a [separate thread](http://stackoverflow.com/a/25797189/4279) or even a [single thread](http://stackoverflow.com/a/25769869/4279) to do it. Also, you don't need `Queue` here, you could use `Event` instead as demonstrated in [my answer](http://stackoverflow.com/a/25797189/4279) – jfs Sep 11 '14 at 21:29
0

To wait for input and to display some random output at the same time, you could use a GUI (something with an event loop):

screenshot

#!/usr/bin/env python3
import random
from tkinter import E, END, N, S, scrolledtext, Tk, ttk, W

class App:
    password = "123456" # the most common password

    def __init__(self, master):
        self.master = master
        self.master.title('To stop, type: ' + self.password)

        # content frame (padding, etc)
        frame = ttk.Frame(master, padding="3 3 3 3")
        frame.grid(column=0, row=0, sticky=(N, W, E, S))
        # an area where random messages to appear
        self.textarea = scrolledtext.ScrolledText(frame)
        # an area where the password to be typed
        textfield = ttk.Entry(frame)
        # put one on top of the other
        self.textarea.grid(row=0)
        textfield.grid(row=1, sticky=(E, W))

        textfield.bind('<KeyRelease>', self.check_password)
        textfield.focus() # put cursor into the entry
        self.update_textarea()

    def update_textarea(self):
        # insert random Unicode codepoint in U+0000-U+FFFF range
        character = chr(random.choice(range(0xffff)))
        self.textarea.configure(state='normal') # enable insert
        self.textarea.insert(END, character)
        self.textarea.configure(state='disabled') # disable editing
        self.master.after(10, self.update_textarea) # in 10 milliseconds

    def check_password(self, event):
        if self.password in event.widget.get():
            self.master.destroy() # exit GUI

App(Tk()).master.mainloop()
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

I want to be able to input words in the console while, at the same time, have random numbers appear in the console.

#!/usr/bin/env python
import random

def print_random(n=10):
    print(random.randrange(n)) # print random number in the range(0, n)

stop = call_repeatedly(1, print_random) # print random number every second
while True:
   word = raw_input("Write something: ") # ask for input until "quit" 
   if word == "quit":
      stop() # stop printing random numbers
      break # quit 

where call_repeatedly() is define here.

call_repeatedly() uses a separate thread to call print_random() function repeatedly.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

you have to run two concurrent threads at the same time in order to get rid of such blocking. looks like there are two interpreters that run your code and each of them executes particular section of your project.

Mehrdad Dadvand
  • 340
  • 4
  • 19