Python-同时运行两个命令 [英] Python - run two commands at the same time

查看:1215
本文介绍了Python-同时运行两个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,在这段代码上遇到了麻烦:

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?

预先感谢

推荐答案

这可以通过使用python中的多处理模块来实现,请找到下面的代码

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

这篇关于Python-同时运行两个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆