gpt4 book ai didi

python - 为什么 tempfile 似乎在 with 语句中删除了自身?

转载 作者:行者123 更新时间:2023-12-01 05:23:26 24 4
gpt4 key购买 nike

该程序是一个旨在规避代理设置的浏览器。正如您所看到的,当数据被处理时,它被放入一个文件中并在默认浏览器中打开。然而,当我在 chrome 中打开它时(我不知道这是否重要),它说:

找不到该网页

未找到该网址的网页: file:///C:/Users/Thornton/appdata/local/temp/tmpreb9zp.html

错误代码:ERR_FILE_NOT_FOUND

这是代码:

import urllib.request
import webbrowser
import tempfile
from tkinter import *


class Browser:

def __init__(self, master):
global e1

self.proxy_handler = urllib.request.ProxyHandler(proxies=None)
self.opener = urllib.request.build_opener(self.proxy_handler)

Label(master, text='Full Path').grid(row=0)
e1 = Entry(master)
e1.grid(row=0, column=1)
Button(master, text='Go', command=self.browse).grid(row=0, column=2)
root.bind('<Return>', self.browse)

@staticmethod
def parsed(data):
initial = str(data)[2:-1]
lines = initial.split('\\n')
return lines

def navigate(self, query):
response = self.opener.open(query)
html = self.parsed(response.read())
return html

def browse(self):
raw_data = self.navigate(e1.get())
clean_data = self.parsed(raw_data)

with tempfile.NamedTemporaryFile(suffix='.html') as cache:
cache.writelines(line.encode('UTF-8') for line in clean_data)
webbrowser.open_new_tab(cache.name)

root = Tk()
root.wm_attributes('-topmost', 1)
app = Browser(root)
root.mainloop()

最佳答案

因为临时文件是 deleted when closed ,并且 with 语句正是这样做的,并且 webbrowser 模块不会等待完成。来自 documentation :

For non-Unix platforms, or when a remote browser is available on Unix, the controlling process will not wait for the user to finish with the browser

关于python - 为什么 tempfile 似乎在 with 语句中删除了自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21878973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com