如何在 jupyter lab 中使用 FileUpload 小部件?

How to use FileUpload widget in jupyter lab?

我想在 jupyter lab 中使用 FileUpload 小部件。 我的笔记本单元格中有以下代码行:

uploader = widgets.FileUpload()
uploader

在 jupyter notebook 中,单元格的输出是一个可点击的按钮,我可以用它来上传文件。在 jupyter lab 中,输出如下:

FileUpload(value={}, description='Upload')

这是 uploader 对象的信息:

Type:           FileUpload
String form:    FileUpload(value={}, description='Upload')
File:           ~/miniconda3/envs/fastai2/lib/python3.7/site-packages/ipywidgets/widgets/widget_upload.py

是否可以让这个小部件在 jupyter lab 上运行?如果是这样,我应该如何进行?

如果您使用的是开箱即​​用的 jupyterlab,默认情况下它没有启用 ipywidgets,您需要在启用扩展后重建它。按照 here:

中的步骤操作
  1. 安装nodeJS
  2. pip install ipywidgets
  3. jupyter nbextension enable --py widgetsnbextension
  4. jupyter labextension install @jupyter-widgets/jupyterlab-manager
  5. (可能需要重新启动您的实验室)

它说较新的 Jupyterlab 已启用它,但我仍然遇到问题,具体取决于平台。手动安装通常是可行的方法。

如果您已经安装了 ipywidgets,您可能需要更新它:

pip install -U ipywidgets

然后安装更新版本的文件:

jupyter nbextension install --py widgetsnbextension

对我来说它在

之后起作用了
pip install jupyterlab-widgets
jupyter labextension install @jupyter-widgets/jupyterlab-manager

另见

https://developer.aliyun.com/mirror/npm/package/@jupyter-widgets/jupyterlab-manager

用法

from ipywidgets import FileUpload
from IPython.display import display
upload = FileUpload(accept='.txt', multiple=True)
display(upload)

with open('z_merged_output.txt', 'wb') as output_file: 
    for uploaded_filename in upload.value:
        content = upload.value[uploaded_filename]['content']   
        output_file.write(content)