python - 如何在 Python 中实现在 Azure Jupyter Notebook 中打开的文件对话框?
问题描述
我的代码:
%gui qt
from PyQt5.QtWidgets import QFileDialog
def gui_fname(dir=None):
"""Select a file via a dialog and return the file name."""
if dir is None: dir ='./'
fname = QFileDialog.getOpenFileName(None, "Select data file...",
dir, filter="All files (*);; SM Files (*.sm)")
return fname[0]
from IPython.display import display
button = widgets.Button(description="Open The File !!")
button.style.button_color = 'yellow'
display(button)
def on_button_clicked(b):
print("Button clicked.")
f=gui_fname()
#import fileplot
#fileplot.load_file(f)
button.on_click(on_button_clicked)
#b1 = Button(description='Open File !!')
#b1.style.button_color = 'yellow'
#b1.on_click(on_button_clicked)
#b1
问题:它在本地 pc python 版本 2.7 os Linux 中运行良好
但是当我尝试在 Azure Jupyter Notebook 中远程实现它时,每次运行代码时内核都会死掉,我无法获得结果。有没有其他方法可以在 ipython 小部件中实现带有 html5 小部件的文件对话框?
我需要什么我需要用户选择他/她的电脑中本地可用的文件。1
解决方案
实际上,您不能在 Azure Jupyter Notebook 上使用任何本机 GUI API,因为 Azure Jupyter Notebook 在没有任何 GUI 支持的远程 Linux 服务器上运行,并且它是用于远程访问的 Web 应用程序。
因此,如果您想为客户端用户显示文件对话框,HTML 文件对话框是您唯一的选择。简单的解决方案是使用模块的display
&HTML
类IPython
来显示一个Choose File
按钮,请看下面的代码&结果。
from IPython.display import display, HTML
display(HTML("""
<input type="file" name="myfile">
"""))
结果是:
对于更复杂的案例,您可以参考这些博客IPython Notebook: Javascript/Python Bi-directional Communication
并Reading files in JavaScript using the File APIs
创建自己的博客。但是,缺少接收和保存上传文件的服务,需要自己实现。fileupload
或者,您可以简单地为 IPython 使用名为(PyPI、GitHub )的现有项目,它是“使用FileReader上传文件的 IPython 笔记本小部件”。
推荐阅读
- sql - 获取每月 25 日后的第 6 个工作日加上 5 个工作日的语法错误
- dart - 在 Dart 中,将动态转换为给定类型或返回 null 的语法好方法?
- javascript - 如何在动态内部级别中仅获取 mongodb 中的一个字段?
- vue.js - 如何在 VueJS 中枚举特定组件类型的子虚拟机?
- amazon-web-services - AWS 事件溯源实施
- node.js - 过滤器电子隐藏的项目
- python - 如何使用 Selenium Python XPATH 获取文本
- json - jq在变量的帮助下更新键和值
- android - Scaffold 主体中的有状态小部件
- sql-server - 如何处理聚合根之间的引用并发?