【问题标题】:How to display text output from function in Panel Pyviz widgets?如何在 Panel Pyviz 小部件中显示函数的文本输出?
【发布时间】:2020-05-07 21:42:29
【问题描述】:

这似乎是一个基本问题,但我尝试了一段时间并没有找到 Pyviz Panel 的解决方案:

我正在尝试通过单击按钮来触发函数,捕获函数的输出并将它们打印在屏幕上所需的位置。

ipywidgets 中的with output 功能是我希望实现的目标的一个很好的例子:

import ipywidgets as widgets
from IPython.display import display

button = widgets.Button(description="Click Me!")
output = widgets.Output()

display(button, output)

def on_button_clicked(b):
    with output:
        print("Button clicked.")

button.on_click(on_button_clicked)

但是,我不知道如何使用 Panel 执行此操作。这是我在 Pyviz Panel 中尝试的一个简单示例。

import panel as pn
pn.extension()
import panel.widgets as pnw

text_output_widget = pnw.StaticText(value='orginal output')
some_button = pnw.Button(name='test',button_type = 'primary')


def callbackfn(WatchedEvents):
    text_output_widget.value = 'new output'
    print('Function successfully run')
    third_party_function() #prints a bunch of stuff


some_button.on_click(callbackfn)
pn.Column(some_button,text_output_widget)

但是,callbackfn() 函数中的print('Function successfully run') 语句的输出在此过程中会丢失。如何捕获此文本输出?

编辑: 在 callbackfn 函数中添加了更多细节,以更具体地表示我的用例。我必须运行由我以外的人编写的函数 (third_party_function())。这些函数打印内容,我不能(不允许)更改这些函数。

【问题讨论】:

  • 当我像这样添加 .show() 时 pn.Column(some_button, text_output_widget).show() 这将打开浏览器选项卡,您实际上可以在按下按钮时在 jupyter 笔记本中看到打印输出被推送。
  • 您的打印功能是否仅用于检查您的功能是否已完成,更像是日志记录?因为 callbackfn 正在工作并更改您的 text_output_widget.value 并且显示此结果。
  • 打印功能更像是我团队中其他人编写的其他功能的替代品。它实际上更像:def callbackfn(WatchedEvents): someone_elses_fn(),我需要能够捕获该输出并将其传送到面板布局的正确部分。
  • 我在执行 .show() 时没有看到。相反,我只会在笔记本上打印<bokeh.server.server.Server at 0x7f5f28afd5c0>。我认为那是因为我没有在本地机器上运行 Jupyter,而是在远程服务器上运行。无论如何,不​​确定如何使用 .show() 检索输出。不过,感谢您的提示。
  • 只是想知道:为什么不创建另一个 text_output_widget 将结果作为变量写入其中。或者使用类似参数的东西:panel.holoviz.org/user_guide/Param.html

标签: panel ipywidgets pyviz holoviz panel-pyviz


【解决方案1】:

您可以在代码中添加print 语句,并在浏览器控制台中查看打印的语句。 您可以在 Firefox 或 Chrome 中通过Ctrl+Shift+I 访问控制台。

我也很沮丧,因为我在使用面板时无法将任何内容打印到单元格输出中。这确实限制了调试能力。感谢 Panel Discourse 平台中的用户向我指出这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多