Python - 同时运行两个命令

时间:2014-09-08 22:16:06

标签: python multithreading pycharm

我是Python的新手,我遇到了这段代码的问题:

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

我希望能够在控制台中输入单词,而同时,控制台中会出现随机数字。但是一旦我输入一个单词,就会出现一个新数字。使这两个命令同时运行的最佳方法是什么?

我是否需要制作一个帖子或者我能做些什么更简单的事情? 如果我需要制作一个帖子,请你就我将如何创建它提供一点帮助?

提前致谢

4 个答案:

答案 0 :(得分:2)

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

#!/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()

答案 1 :(得分:0)

要等待输入并同时显示一些随机输出,您可以使用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()

答案 2 :(得分:0)

  

我希望能够在控制台中输入单词,同时在控制台中显示随机数字。

#!/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 

其中call_repeatedly() is define here

call_repeatedly()使用单独的线程重复调用print_random()函数。

答案 3 :(得分:0)

你必须同时运行两个并发线程才能摆脱这种阻塞。看起来有两个解释器运行您的代码,每个解释器都执行项目的特定部分。