2016-02-25 17 views
2

如何在下面的例子中移動滑塊時更新python變量extern_python_variableextern_python_variable的值應始終爲f(滑塊的實際位置)。謝謝!如何在散景中的customJS函數中更新全局python變量?

from bokeh.io import vform 
from bokeh.models import CustomJS, ColumnDataSource, Slider 
from bokeh.plotting import Figure, output_file, show 

output_file("callback.html") 


x = [x*0.005 for x in range(0, 200)] 
y = x 

extern_python_variable=0 

source = ColumnDataSource(data=dict(x=x, y=y)) 

plot = Figure(plot_width=400, plot_height=400) 
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) 

callback = CustomJS(args=dict(source=source), code=""" 
     var data = source.get('data'); 
     var f = cb_obj.get('value') 
     x = data['x'] 
     y = data['y'] 
     for (i = 0; i < x.length; i++) { 
      y[i] = Math.pow(x[i], f) 
     } 
     source.trigger('change'); 
    """) 

slider = Slider(start=0.1, end=4, value=1, step=.1, title="power", callback=callback) 

test=source.to_df() 

layout = vform(slider, plot) 

show(layout) 
+0

這段代碼的輸出是一個HTML文件,它包含的JavaScript交互機械。因此,它將在瀏覽器中運行,它將在瀏覽器中運行JavaScript,它不會運行任何Python例程。我想知道你打算用extern_python_variable做什麼?如果你想監視f的值,你可以在瀏覽器中打開一個javascript控制檯,你可以使用console.log(variable_to_monitor)轉儲任何信息。 –

+0

上面的代碼應該只是一個簡單的例子。實際上,我想從python變量中的選擇中保存rect屬性,並且需要這些變量用於進一步的面向數據庫的計算,而這些變量不能在customJS函數中完成。 – justus

回答

1

我看到最多三個方面做你想做什麼:

1)使用背景虛化服務器,你可以到工具的事件,並同步與蟒蛇進行計算響應。使用一個XMLHttpRequest(見Running a Bokeh Server

2)如果你仍然想使用靜態的HTML頁面,然後,一個工具的事件後,您可以將數據發送到服務器(可以是localhost)(見Using XMLHttpRequest),由它來等待服務器的響應。服務器可以有一個CGI python腳本(請參閱Python CGI Programming)讀取由XMLHttpRequest發送的數據,並將一些值返回到發出請求的CustomJS。

3)第三種基本方式可能是打開一個空網頁並使用document.write函數轉儲數據(請參閱Window open() Method)。然後,將數據複製並粘貼到python腳本或ipython筆記本中進行分析。

+0

太棒了!謝謝巴勃羅。我會用Bokeh Server測試你的建議。 – justus

0

我喜歡散景嵌入示例中的widget腳本中介紹的方法。

CustomJS回調只在瀏覽器中執行(不執行python代碼)。見here

舉例來說,使用背景虛化的服務器,你可以添加以下代碼,以獲得蟒蛇回調:

def update(attr, old, new): 
    # your custom python code 

slider = Slider(start=0.1, end=4, value=1, step=.1, title="power") 
slider.on_change('value', update)