我需要分离一个在后台连续运行的单个线程,并在每次输入时将一组10个数字/字符返回给主程序而不用占用主程序。仅供参考 - 以下代码现在可以在MS Windows和Linux上运行。 以下测试python 2.7x代码有效:
#!/usr/bin/env python
import thread
import time
try:
from msvcrt import getch # try to import Windows version
except ImportError:
def getch(): # define non-Windows version
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 ch
char = None
def keypress():
global char
char = getch()
thread.start_new_thread(keypress, ())
while True:
if char is not None:
print "Key pressed is %s" % char
char = None
else:
print "\nNo keys pressed, continue program is running\n"
time.sleep(2)
global char
char = getch()
但是当我把它分成两个部分,main.py和functions.py时,似乎没有返回全局变量:
main.py
#!/usr/bin/env python
# main
from functions import *
import thread
import time
thread.start_new_thread(keypress, ())
while True:
if char is not None:
print "Key pressed is %s" % char
break
# char = None
else:
print "\nNo keys pressed, continue program is running\n"
time.sleep(1)
functions.py
#!/usr/bin/env python
#functions.py
char = None
try:
from msvcrt import getch # try to import Windows version
except ImportError:
def getch(): # define non-Windows version
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 ch
def keypress():
global char
char = getch()
我认为问题是全局变量char没有通过访问keypress函数的线程返回主程序。 任何帮助将不胜感激。 TIA
答案 0 :(得分:0)
我的主要功能和功能不起作用的原因是因为在调用函数之前我没有声明char在main中是全局的。更正后的代码如下所示,适用于我:
主
#!/usr/bin/env python
# main
from functions import *
import thread
import time
global char # must be declared as global before any functions that access it
char = None
thread.start_new_thread(keypress, ())
while True:
global char
if char is not None:
print "Key pressed is %s" % char
char = None
else:
print "\nNo keys pressed, continue program is running\n"
time.sleep(2)
char = getch()
功能
#!/usr/bin/env python
#functions.py
char = None
try:
from msvcrt import getch # try to import Windows version
except ImportError:
def getch(): # define non-Windows version
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 ch
def keypress():
global char
char = getch()