我已经尝试过th1.join,但是那没有用,我不知道还能尝试什么。
另外,我需要将其作为一个函数
这是我的代码:
在Linux上,只有添加两件事,它才对我有用
循环后我必须设置stoprun = 1
c = InKey()
while not c == 27:
c = InKey()
stoprun = 1 # set after loop
我必须在线程中使用print()
-可能它需要\n
(或者只是需要此IO函数来更改正在运行的线程)
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()
在stop
中,您写:
while not c == 27:
c = InKey()
stoprun = 1
return
stoprun = 1
将创建一个新的本地名称stoprun
,而不用修改全局变量,因为您从未将stoprun
标记为全局。这样做:
def stop():
global stoprun
... # your code