1

I currently have code that reads raw content from a file chosen by the user:

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()

But, sometimes people open big files that take more than 2 seconds to open. Is there a callback for FileObject.read([size])? For people who don't know what a callback is, it's a operation executed once another operation has executed.

4

2 回答 2

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
于 2013-07-03T20:36:33.100 回答
0

提问者已解决的答案

嗯,一开始我搞错了。tkFileDialog.askopenfile()不读取文件,而是FileObject.read()读取文件,并阻塞代码。我根据@kindall找到了解决方案。不过,我不是 Python 方面的完整专家。

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

谢谢亲切!解决的代码:

def choosefile():
filec = tkFileDialog.askopenfile()
filecontents = filec.read()
于 2013-07-03T23:18:01.050 回答