我正在调用Python中的一个函数,我知道它可能会停止并迫使我重新启动脚本.
如何调用该函数或我将其包装成什么,以便如果它花费的时间超过5秒,脚本会取消它并执行其他操作?
你会如何提示用户输入一些信息但是在N秒后超时?
谷歌在http://mail.python.org/pipermail/python-list/2006-January/533215.html上指向了一个关于它的邮件线程,但似乎没有用.超时发生的语句,无论是sys.input.readline还是timer.sleep(),我总是得到:
<type'exception.TypeError'>:[raw_]输入最多需要1个参数,得2
以某种方式,除了没有抓住.
我希望能够做的是使用输入询问用户问题.例如:
print('some scenario')
prompt = input("You have 10 seconds to choose the correct answer...\n")
Run Code Online (Sandbox Code Playgroud)
然后如果时间流逝打印出类似的东西
print('Sorry, times up.')
Run Code Online (Sandbox Code Playgroud)
任何指导我正确方向的帮助将不胜感激.
在python中,有没有办法在等待用户输入时计算时间,以便在30秒后raw_input()自动跳过该函数?
我试图在Windows下运行以下python服务器:
"""
An echo server that uses select to handle multiple clients at a time.
Entering any line of input at the terminal will exit the server.
"""
import select
import socket
import sys
host = ''
port = 50000
backlog = 5
size = 1024
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host,port))
server.listen(backlog)
input = [server,sys.stdin]
running = 1
while running:
inputready,outputready,exceptready = select.select(input,[],[])
for s in inputready:
if s == server:
# handle the server socket
client, address = server.accept() …Run Code Online (Sandbox Code Playgroud) 我想使用倒数计时器功能在Tkinter中设置标签.现在它所做的就是在达到10时将标签设置为"10"并且我真的不明白为什么.此外,即使我将计时器打印到终端而不是"时间到了!" 有点从不打印.
import time
import tkinter as tk
class App():
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(text="null")
self.label.pack()
self.countdown()
self.root.mainloop()
# Define a timer.
def countdown(self):
p = 10.00
t = time.time()
n = 0
# Loop while the number of seconds is less than the integer defined in "p"
while n - t < p:
n = time.time()
if n == t + p:
self.label.configure(text="Time's up!")
else:
self.label.configure(text=round(n - t))
app=App()
Run Code Online (Sandbox Code Playgroud) 我已经读过这种技术来超时阻止IO操作,问题是它似乎不起作用.例如:
import thread, threading
def read_timeout(prompt, timeout=10.0):
timer = threading.Timer(timeout, thread.interrupt_main)
s = ''
timer.start()
try:
s = raw_input(prompt)
except KeyboardInterrupt:
print 'operation timed out.'
timer.cancel()
return s
s = read_timeout('enter input: ')
if s:
print 'you entered: %s' % s
Run Code Online (Sandbox Code Playgroud)
这不会在raw_input()返回之前中断主线程.任何帮助表示赞赏.
使用os.kill(os.getpid(), signal.SIGINT)而不是thread.interrupt_main()似乎工作(至少在Linux上,这不会给我我最初想要的可移植性).但是,我仍然想知道为什么上面的代码不起作用.
我正在使用Python 3,我想编写一个程序,在一定时间内要求多个用户输入.这是我的尝试:
from threading import Timer
##
def timeup():
global your_time
your_time = False
return your_time
##
timeout = 5
your_Time = True
t = Timer(timeout, timeup)
t.start()
##
while your_time == True:
input()
t.cancel()
print('Stop typing!')
Run Code Online (Sandbox Code Playgroud)
问题是,即使时间到了,代码仍然等待输入.我希望循环在时间用完时完全停止.我该怎么做呢?谢谢!