2014-09-08 3 views
0

동시에 실행 두 명령 : 상기파이썬 내가 파이썬에 새로운 오전과 코드의이 부분에 문제가 있어요

while true: 
    rand = random.choice(number) 
    print(rand)    
    enter_word = input("Write something: ") 
    time.sleep(5) 
내가 콘솔 동안 입력 단어 수 있도록하려면

, 과 같은 시간에 임의의 숫자가 콘솔에 나타납니다. 그러나 한 번 단어를 입력하면 새로운 번호가 나타납니다. 이 두 명령을 동시에 실행하는 가장 좋은 방법은 무엇입니까?

스레드를 만들어야합니까, 아니면 내가 할 수있는 것이 더 있습니까? 그리고 스레드를 만들 필요가 있다면 어떻게 만드는지 약간의 도움을 줄 수 있습니까? 사전에

감사

+0

GUI 작성을 고려 했습니까? 입력을위한 텍스트 필드와 출력을위한 텍스트 영역은 무엇입니까? – jfs

+0

나는 결국 GUI를 만들 예정이다. 하지만이게 내 문제를 해결할 수 있을까? – user2456977

+1

GUI는 일반적으로 이벤트 루프를 사용하여 일을 동시에 처리하는 등 간단한 작업을 수행합니다. 예를 들어 텍스트 필드가 입력 대기하는 동안 텍스트 영역에 임의의 숫자를 채우는 함수를 반복적으로 호출합니다. – jfs

답변

1

이 될 수 있습니다 파이썬에서 다중 처리 모듈을 사용하여 달성 한 코드는 다음과 같습니다.

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

숫자를 인쇄하고 입력을 병렬로 기다리기 위해 별도의 * 프로세스 *가 필요하지 않습니다. [별도의 스레드] (http://stackoverflow.com/a/25797189/4279) 또는 [단일 스레드] (http://stackoverflow.com/a/25769869/4279)를 사용해도됩니다. 또한 여기에'대기열 '이 필요하지 않습니다. 대신 [내 대답] (http://stackoverflow.com/a/25797189/4279)에 설명 된대로'이벤트 '를 사용할 수 있습니다. – jfs

0

당신이 (something with an event loop를) 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() 
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() 함수를 반복적으로 호출합니다.

0

이러한 차단을 없애려면 동시에 두 개의 동시 스레드를 실행해야합니다. 코드를 실행하는 두 개의 인터프리터가 있고 각각이 프로젝트의 특정 섹션을 실행하는 것처럼 보입니다.

관련 문제