2011-11-30 2 views
1

어제는 이미 this에 대한 질문을했지만, 지금은 또 다른 :) 내 터미널 애플 리케이션을위한 텍스트 효과 형식 클래스를 작성하려고 - 위치 커서 같은 것들을 않습니다 , '@', 임의의 경우, 색상 사이클링 및 기타 재미있는 것들 (부분적으로는 파이썬에 대한 나의 학습을 돕고 부분적으로는 유용성을 돕기 위해)이 선행하는 색으로 에코 문자열 내부의 색상 선택을 취소 할 수 있습니다. 수업은 스레드가 아닐까요? 어떻게할까요? 나는이 스피너가 작동하는 순간 (전체 코드 here), 여러 번 호출하려고합니다. 이 같은 :회 전자 클래스 스레드 오류 - 하나의 스레드 만 허용

s=spin() 
s.echo('@@') # clears screen 
# at the moment - here i get an error because only one thread can be started 
s.echo('@red this is red @green green etc...') 

당신은 페이스트 빈 보면 에코 기능을 사용하면 물건을 많이 볼 수 있습니다 않는, 그래서 난 꽤 것을 호출 할 필요가 있지만, 여러 통화 허용 '하나의 스레드'결과 오류. 아마도 내가 다른 방식으로해야 할 것입니다. 이것은 pastebin 물건 이전의 기본 오래된 코드였습니다.

spinner="▏▎▍▌▋▊▉█▉▊▌▍▎" #utf8 

#convert the utf8 spinner string to a list 
chars=[c.encode("utf-8") for c in unicode(spinner,"utf-8")] 

class spin(threading.Thread): 

    def __init__(self): 
     super(spin,self).__init__() 
     self._stop = False 

    def run (self): 
     pos=0 
     while not self._stop: 
      sys.stdout.write("\r"+chars[pos]) 
      sys.stdout.flush() 
      time.sleep(.15) 
      pos+=1 
      pos%=len(chars) 

    def cursor_visible(self): 
     os.system("tput cvvis") 
    def cursor_invisible(self): 
     os.system("tput civis") 
    def stop(self): 
     self._stop = True 
    def stopped(self): 
     return self._stop == True 

답변

0

달리 메소드에서 실제로 실행중인 메소드 만 다른 스레드에서 실행 중입니다. 코드의 문제는 스레드를 두 번 이상 시작하려고하는 것입니다 (echo 메서드에서). 시작하기 전에 스레드가 이미 시작되었는지 확인해야합니다 (self._stop 확인).

def echo (self, arg=None, sep=' ', end='\n', rndcase=True, txtspeed=0.03, bnum=0, spsw=True): 
    print cursave, 
    self.cursor_invisible() 

    # do you have to do all this ? 
    # c0m4: Only if you need all of those to be accessible for the spin object when echo ends 
    self.arg=arg 
    self.sep=sep 
    self.end=end 
    self.rndcase=rndcase 
    self.txtspeed=txtspeed 
    self.bnum=bnum 
    self.spsw=spsw 

    pos=0 
    cmd, txt = [reset], [] 
    spsw=True 
    last_colour='' 
    txtpos=0 
    if arg: 

# test if spinner is wanted and set the text position to be moved across a bit to allow for it 
    if spsw is True: 
    txtpos=4 
    self.start() 

문제가 발생한 곳의 마지막 줄. 스레드를 한 번 더 시작하는 것은 불가능합니다. 따라서 스레드를 다시 시작하기 전에 스레드가 실행 중인지 확인해야합니다.

self.running = True 

그리고이 같은 객체의 상태 (스레드 실행 여부)을 확인 할 수 있습니다 init 메소드에

self.running = False 

같은 것을 추가 한 다음 실행 방법을 설정합니다

if not self.running: 
    self.start() 

에 관계없이 실행의 초기 부분을 실행해야하는 경우는 다음과 같이 별도의 방법에 그것을 넣어해야합니다

,
def resetThread(): 
    self.pos = 0 
+0

내 대답이 업데이트되었습니다. – c0m4

+0

ive는 그것을 재설정하려고 시도하는 다양한 방법을 시도했지만, 그것을 좋아하지 않는 것처럼 보입니다. –

+0

한 번 이상 스레드를 시작할 수 없습니다. 나는 나의 대답을 다시 업데이트했다. – c0m4

관련 문제