user2456977 user2456977 - 1 month ago 4
Python Question

Python - run two commands at the same time

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

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

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

Ram Ram

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

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))
      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
   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
   #Block the calling thread until the process whose join() 
   #method is called terminates or until the optional timeout occurs.