Python - run two commands at the same time(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 - 同时运行两个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!