从线程化python函数返回全局变量

2024-04-25 04:07:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要剥离一个线程,它将在后台连续运行,并在每次输入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公司


Tags: pyimportversionwindowsdefstdinsysold
1条回答
网友
1楼 · 发布于 2024-04-25 04:07:37

我的分割main和函数不能工作的原因是我在调用函数之前没有声明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()

功能

^{pr2}$

相关问题 更多 >