Как я могу остановить запуск моей анимации, когда stoprun = 1? - PullRequest
0 голосов
/ 19 февраля 2020

Я пробовал th1.join, но это не сработало, и я не знаю, что еще попробовать.

Кроме того, мне нужно, чтобы это была одна функция

Вот мой код:

https://repl.it/@JamesGordon1 / JuicyScentedCrypto (извините, слишком долго для публикации)

Ответы [ 2 ]

1 голос
/ 20 февраля 2020

Вкл. Linux У меня это работает, только если я добавлю две вещи

  1. Я должен установить stoprun = 1 после l oop

    c = InKey()
    while not c == 27:
        c = InKey()
    
    stoprun = 1 # set after loop
    
  2. Мне нужно использовать print() в потоке - возможно, ему нужно \n (или просто нужна эта функция ввода-вывода для изменения запущенного потока)

    if stoprun == 1: # True
        print()  # have to send `\n`
        return
    

Я не знаю, зачем это нужно, но потоки в Python не работают одновременно - один поток блокирует другие - и, возможно, эти элементы останавливают один поток и позволяют запустить другой поток.


Конечно, это также нужно global stoprun внутри stop()


from threading import Thread

import time
import sys
import os

# --- classes ---

class _GetCh:
    def __init__(self):
      try:
        self.impl = _GetChWindows()
      except ImportError:
        try:
          self.impl = _GetChMacCarbon()
        except ImportError:
          self.impl = _GetChUnix()
    def __call__(self):
      return self.impl()

class _GetChWindows:
    def __init__(self):
      import msvcrt
    def __call__(self):
      import msvcrt
      if msvcrt.kbhit():
        while msvcrt.kbhit():
          ch = msvcrt.getch()
        while ch in b'\x00\xe0':
          msvcrt.getch()
          ch = msvcrt.getch()
        return ord( ch.decode() )
      else:
        return -1

class _GetChMacCarbon:
    def __init__(self):
      import Carbon
      Carbon.Evt
    def __call__(self):
      import Carbon
      if Carbon.Evt.EventAvail(0x0008)[0]==0:
        return ""
      else:
        (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
        return msg & 0x000000FF

class _GetChUnix:
    def __init__(self):
      import tty, sys, termios
    def __call__(self):
      import sys, tty, termios
      fd = sys.stdin.fileno()
      old_settings = termios.tcgetattr(fd)
      try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
      finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
      return ord(ch)

InKey = _GetCh()

# --- main ---

stoprun = 0 # False

def load_animation():
  load_str = "starting your console application "
  ls_len = len(load_str) 
  animation = "|/-\\"
  anicount = 0      
  i = 0
  while True:
    time.sleep(0.075) 
    load_str_list = list(load_str) 
    x = ord(load_str_list[i]) 
    y = 0                           
    if x != 32 and x != 46:          
      if x>90: 
        y = x-32
      else: 
        y = x + 32
      load_str_list[i]= chr(y) 
    res =''          
    for j in range(ls_len): 
      res = res + load_str_list[j] 
    sys.stdout.write("\r"+res + animation[anicount]) 
    sys.stdout.flush() 
    load_str = res 
    anicount = (anicount + 1)% 4
    i =(i + 1)% ls_len
    if stoprun == 1: # True
        print()  # have to send `\n`
        return

def stop():
  global stoprun

  print ("Press Esc to exit")

  c = InKey()
  while not c == 27:
    c = InKey()

  stoprun = 1 # have to be after loop

  return

th1 = Thread(target=load_animation)
th1.start()
stop()
#th1.join()
0 голосов
/ 19 февраля 2020

В stop вы пишете:

  while not c == 27:
    c = InKey()
    stoprun = 1
  return

stoprun = 1 создаст новое локальное имя stoprun вместо изменения глобальной переменной, поскольку вы никогда не отмечали stoprun global. Сделайте это:

def stop():
    global stoprun
    ... # your code
...