我需要剥离一个线程,它将在后台连续运行,并在每次输入10个数字/字符时将它们返回给主程序,而不需要占用主程序。下面的FYMS和Linux代码现在都可以用了。 下面的测试python2.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()
但当我把它分成两部分时,主.py以及函数.py似乎没有返回全局变量:
在主.py在
^{pr2}$在函数.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公司
我的分割main和函数不能工作的原因是我在调用函数之前没有声明char在main中是全局的。更正后的代码如下,适用于我:
主
功能
^{pr2}$相关问题 更多 >
编程相关推荐