我正在忙着写一个小游戏服务器试用烧瓶.游戏通过REST向用户公开API.用户可以轻松执行操作和查询数据,但是我想在app.run()循环之外为"游戏世界"提供服务以更新游戏实体等.鉴于Flask实施得非常干净,我想要看看Flask是否有办法做到这一点.
在我的代码中有一个与套接字相关的函数调用,该函数来自另一个模块,因此无法控制,问题是它偶尔会阻塞几个小时,这是完全不可接受的,我如何限制代码中的函数执行时间?我想解决方案必须使用另一个线程.
我需要在 Mac 和 Windows 上为 python 3 提供定时输入,如果用户没有时间,它会自动选择其中一个选项。我见过的问题的所有其他答案只有在用户按“Enter”键后才会终止。无论是否按下“Enter”键,我都需要它终止。
例如,在我的国际象棋程序中,如果5秒后没有输入,我需要它自动选择“Q”。另外,如果输入不在 [“Q”,“R”,“B”,“N”] 中,那么我还需要它来选择“Q”。
下面的代码不起作用。它会要求输入然后永远等待;计时器根本不工作。
def countdown():
global timer
timer = 5
for x in range(timer):
timer -= 1
time.sleep(1)
countdownThread = threading.Thread(target=countdown)
countdownThread.start()
while timer > 0:
promotedPiece = input("Promote to Q, R, B or N? > ").upper()
if timer == 0:
break
if timer == 0:
if promotedPiece not in ["Q", "R", "B", "N"]: # If not valid input, choose Queen
promotedPiece = "Q"
print("Queen auto selected")
Run Code Online (Sandbox Code Playgroud) python multithreading timer python-multithreading python-3.x
我正在尝试了解OS概念和Python库。
我遇到了Python文档https://docs.python.org/3/library/signal.html链接中提到的特定示例,该示例在Windows上不适合我。
import signal, os
def handler(signum, frame):
print('Signal handler called with signal', signum)
raise OSError("Couldn't open device!")
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
# This open() may hang indefinitely
fd = os.open('/dev/ttyS0', os.O_RDWR)
signal.alarm(0) # Disable the alarm
Run Code Online (Sandbox Code Playgroud)
singal.SIGALRM在Windows上不起作用有任何特定原因吗?
自动完成甚至在Pycharm IDE中显示SIGALRM(我假设如果显示这样的变量或函数)。
但是,当我运行该程序时,它在Windows上给了我以下错误。我还没有在Linux上检查过。
Traceback (most recent call last):
File "C:/Users/preddy53/Desktop/syst.py", line 8, in <module>
signal.signal(signal.SIGALRM, handler)
AttributeError: module 'signal' has no attribute 'SIGALRM'
Run Code Online (Sandbox Code Playgroud)
我在哪里做错了?它仅适用于操作系统吗?
即使我在Cygwin中运行python脚本,Python信号似乎也无法在Windows上运行.我得到了AttributeError: 'module' object has no attribute SIGALRM
有没有办法在Windows上解决这个问题.我只是在http://docs.python.org/2/library/signal.html末尾运行示例
我有一个函数,运行时间不会太长。我想为其设置一个超时限制。我可以在互联网上找到一种建议的解决方案。请参阅以下 SO 帖子。函数调用超时
该解决方案使用信号,这在 Windows 上不可用。信号也有类似的用途来制作自动收报机,它有一个 Windows 端口,如这篇 SO 帖子中所解释的:python:windows 相当于 SIGALRM这不是直接超时的答案,但可以适应超时。它是为 python 2.7 编写的。
由于答案大约有 10 年历史,我的问题是:是否有更现代的 python(例如 python 3.7)方法来创建上下文管理器/装饰器/类似包装器,将“普通函数”制作为超时限制函数视窗系统?