메인이 여전히 파이썬에서 실행되는 동안 스레딩을 사용하여 사용자 입력을 실시간으로 얻는 방법

VValkyrja

WHILE 루프에서 두 가지 기능을 실행하고 싶습니다. 하나는 기본 기능으로 매번 실행되는 기능이고 다른 하나는 user_input 기능입니다. 사용자가 'disarm'을 입력하면 프로그램이 user_input 기능을 실행할 수 있습니다. 이 두 함수는 WHILE 루프에 필요하므로 항상 실행할 수 있습니다.

이 작업을 수행하는 함수를 작성하려면 어떻게해야합니까?

실시간이므로 스레딩에서 time.sleep을 추가 할 수 없습니다.

감사.

import threading

class BackInput(threading.Thread):
    def __init__(self):
        super(BackInput, self).__init__()


    def run(self):
        self.input = raw_input()

while True:
    threading1 = BackInput()
    threading1.start()
    threading1.join()
    if threading1.input == 'disarm':
        print 'Disarm'
        break
    print 'Arm'

이 코드에서 프로그램은 매초마다 Arm을 인쇄해야하며, disarm을 입력하면 Disarm을 인쇄하고 중단 할 수 있습니다.

마이클 닐론

당신은 정말로 더 구체적이어야합니다. 스레드에 있어야하는 이유는 무엇입니까? 시도한 내용을 보여 주거나 달성하려는 내용을 자세히 설명해야합니다.

현재 설정에서는 스레드를 루프 안에 넣으므로 각 사용자 입력과 독립적으로 실행할 수 없습니다.

edited : 다음은 게시물 편집 및 댓글을 기반으로 한 정리 된 코드입니다.

import threading
import time
import sys

def background():
        while True:
            time.sleep(3)
            print 'disarm me by typing disarm'


def other_function():
    print 'You disarmed me! Dying now.'

# now threading1 runs regardless of user input
threading1 = threading.Thread(target=background)
threading1.daemon = True
threading1.start()

while True:
    if raw_input() == 'disarm':
        other_function()
        sys.exit()
    else:
        print 'not disarmed'

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관