Python - run two commands at the same time

后端 未结 4 414
生来不讨喜
生来不讨喜 2021-01-07 08:05

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

while true:
   rand = random.choice(number)
   print(rand)             
   enter_word = inp         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 08:43

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

提交回复
热议问题