在浏览器中编写Python时,必须重新考虑操作的执行方式.通常,Python程序是程序化的.基于浏览器的应用程序是异步的.
第一步是启用异步功能:
import asyncio
基于浏览器的程序无法直接访问本地文件系统.你的代码没有做你认为的事情.
def readfile(filename):
with open(filename) as mfile:
head = [next(mfile) for x in range(1,5)]
print(head)
您的代码正在从允许的浏览器虚拟文件系统中读取.您试图从`元素处理事件,但试图访问其他位置.
注意:我不知道"filename"的文件内容是什么,所以我没有在读取文件后加入您的代码.
你的代码无法读取文件.您必须要求浏览器读取应用程序的文件.这是通过FileReader类执行的.
例子:
async def process_file(event):
# Currently, PyScript print() does not work in this
# type of code (async callbacks)
# use console.log() to debug output
fileList = event.target.files.to_py()
for f in fileList:
data = await f.text()
document.getElementById("content").innerHTML = data
# Add your own code to process the "data" variable
# which contains the content of the selected file
另一个问题是,您正在将Python函数作为回调传递.那是行不通的.相反,必须调用create_proxy()
为Python函数创建回调代理.浏览器将调用代理,然后代理将调用Python函数.
例子:
# Create a Python proxy for the callback function
# process_file() is your function to process events from FileReader
file_event = create_proxy(process_file)
# Set the listener to the callback
document.getElementById("myfile").addEventListener("change", file_event, False)
我把这个解决方案的副本放在了我的网站上.你可以右键点击页面下载源代码.
File Example Demo
完整解决方案:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>File Example</title>
</head>
<body>
<p>This example shows how to read a file from the local file system and display its contents</p>
<br />
<p>Warning: Not every file type will display. PyScript removes content with tags such as XML, HTML, PHP, etc. Normal text files will work.</p>
<br />
<p>No content type checking is performed to detect images, executables, etc.</p>
<br />
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
<br />
<br />
<div id="print_output"></div>
<br />
<p>File Content:</p>
<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:600px; resize:both">
<div id="content">
</div>
</div>
<py-script output="print_output">
import asyncio
from js import document, FileReader
from pyodide import create_proxy
async def process_file(event):
fileList = event.target.files.to_py()
for f in fileList:
data = await f.text()
document.getElementById("content").innerHTML = data
def main():
# Create a Python proxy for the callback function
# process_file() is your function to process events from FileReader
file_event = create_proxy(process_file)
# Set the listener to the callback
e = document.getElementById("myfile")
e.addEventListener("change", file_event, False)
main()
</py-script>
</body>
</html>