简体   繁体   English

Python file.read()回调

[英]Python file.read() Callback

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. 但是,有时人们打开大文件需要2秒钟以上的时间才能打开。 Is there a callback for FileObject.read([size]) ? 是否有FileObject.read([size])的回调? For people who don't know what a callback is, it's a operation executed once another operation has executed. 对于不知道回调是什么的人,这是一次执行完另一个操作后执行的操作。

Slightly modified from the docs: 从文档中略作修改:

#!/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

Answer resolved by asker 提问者回答的答案

Hm, I made a mistake at first. 嗯,我起初犯了一个错误。 tkFileDialog.askopenfile() does not read the file, but FileObject.read() reads the file, and blocks the code . tkFileDialog.askopenfile()不读取文件,但是FileObject.read()读取文件,并阻止代码 I found the solution according to @kindall . 我根据@kindall找到了解决方案。 I'm not a complete expert at Python, though. 我不是Python的专家。

Your question seems to assume that Python will somehow start reading your file while some other code executes, and therefore you need to wait for the read to catch up. 您的问题似乎假设Python将以某种方式在执行其他代码的同时开始读取文件,因此您需要等待读取赶上来。 This is not even slightly true; 这甚至不是真的。 both open() and read() are blocking calls and will not return until the operation has completed. open()和read()都将阻止调用,并且在操作完成之前不会返回。 Your sleep() is not necessary and neither is your proposed workaround. 您的sleep()不是必需的,建议的解决方法也不是。 Simply open the file and read it. 只需打开文件并阅读。 Python won't do anything else while that is happening. 在这种情况下,Python不会做其他任何事情。

Thanks kindall! 谢谢kindall! Resolved code: 解决的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM