Python文件.read()催缴

2024-04-19 11:58:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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])的回调?对于不知道回调是什么的人来说,它是在执行另一个操作后执行的操作。在


Tags: 文件theto代码用户内容readdef
2条回答

问题解决答案

嗯,一开始我犯了个错误。tkFileDialog.askopenfile()不读取文件,但FileObject.read()读取文件,并阻止代码。我根据@kindall找到了解决方案。不过,我不是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. This is not even slightly true; both open() and read() are blocking calls and will not return until the operation has completed. Your sleep() is not necessary and neither is your proposed workaround. Simply open the file and read it. Python won't do anything else while that is happening.

谢谢你!解析代码:

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

根据文件稍作修改:

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

相关问题 更多 >