Python file.read()回调

时间:2013-07-03 20:30:45

标签: python tkinter tk

我目前有代码从用户选择的文件中读取原始内容:

def choosefile():
    filec = tkFileDialog.askopenfile()
    # Wait a few to prevent attempting to displayng the file's contents before the entire file was read.
    time.sleep(1)
    filecontents = filec.read()

但是,有时人们会打开需要超过2秒才能打开的大文件。是否有FileObject.read([size])的回调?对于那些不知道回调是什么的人来说,这是一次执行另一个操作后执行的操作。

2 个答案:

答案 0 :(得分:0)

从文档略微修改:

#!/usr/bin/env python

import signal, sys

def handler(signum, frame):
    print "You took too long"
    sys.exit(1)

f = open(sys.argv[1])

# Set the signal handler and a 2-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(2)

contents = f.read()

signal.alarm(0) # Disable the alarm

print contents

答案 1 :(得分:0)

答案由提问者解决

嗯,我一开始犯了一个错误。 tkFileDialog.askopenfile()未读取文件,但FileObject.read()读取文件,阻止代码。我根据@kindall找到了解决方案。不过,我不是Python的完全专家。

  

您的问题似乎假设Python会在某些其他代码执行时以某种方式开始读取您的文件,因此您需要等待读取才能赶上。这甚至都不是真的; open()和read()都是阻塞调用,在操作完成之前不会返回。您的睡眠()不是必需的,也不是您提议的解决方法。只需打开文件并阅读即可。在发生这种情况时,Python不会做任何其他事情。

非常感谢!已解决的代码:

def choosefile():
filec = tkFileDialog.askopenfile()
filecontents = filec.read()