Python - 同时运行两个命令

2 投票
4 回答
13167 浏览
提问于 2025-04-20 13:24

我刚开始学习Python,遇到了一段代码的问题:

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

我想在控制台输入单词的同时,让随机数字也在控制台出现。但是只有在我输入一个单词后,新的数字才会出现。有什么好的方法可以让这两个操作同时进行吗?

我需要创建一个线程吗,还是有更简单的方法可以做到?如果我需要创建线程的话,能不能给我一点帮助,教我怎么做?

提前谢谢你!

4 个回答

0

你需要同时运行两个线程,这样才能避免这种阻塞。听起来就像有两个解释器在运行你的代码,每个解释器负责执行你项目中的特定部分。

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() 在这里定义

call_repeatedly() 使用一个单独的线程来不断调用 print_random() 函数。

0

如果你想在等待输入的同时显示一些随机的输出,可以使用图形用户界面(GUI),也就是有事件循环的那种东西:

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

这可以通过使用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()

撰写回答