Вкл. Linux У меня это работает, только если я добавлю две вещи
Я должен установить stoprun = 1
после l oop
c = InKey()
while not c == 27:
c = InKey()
stoprun = 1 # set after loop
Мне нужно использовать 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()