输入动态文件夹名称以在bokeh中加载csv文件

时间:2019-03-16 07:16:48

标签: python bokeh

不同的CSV文件位于具有用户名的不同文件夹中,因此我想通过使用文件夹名(用户名)动态加载csv文件。我正在使用csv文件生成一些分析。我在bokeh中使用了TextInput Glyph,但不知道如何赋予此输入值文本以加载csv文件。有什么办法可以散景吗? 下面是代码,我如何加载CSV文件。必须根据我们的输入动态更改代码中的“用户”。

package org.apache.livy.examples.ReadMongo;

import net.butfly.albacore.utils.logger.Logger;
import org.apache.livy.LivyClient;
import org.apache.livy.LivyClientBuilder;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import org.apache.livy.examples.*;

public class ReadMongoApp {
    private static final Logger logger = Logger.getLogger(ReadMongoApp.class);
    private static final URI uri;
    static {
        try {
            uri = new URI("http://myIp:8998/");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        LivyClient client = new LivyClientBuilder().setConf("kind", "spark").setURI(uri).build();
        try {
            init(client);
            ReadMongoJob job = new ReadMongoJob();
            PiJob piJob = new PiJob("alla");
//          JobHandle<String> jobHandle = client.submit(job)
//          logger.info("------------------" + jobHandle.getState());
            String json;
            try {
                json = client.submit(job).get();
            } catch (InterruptedException | ExecutionException e) {
                throw new IOException(e);
            }
            logger.info("job result:" + json);
        } finally {
            client.stop(true);
        }
    }

    private static void init(LivyClient client) {
        final String dir = System.getProperty("user.dir");
        Path curr = Paths.get(dir);
        Path jar = curr.resolve("target" + File.separator + "livy-examples-0.6.0-incubating-SNAPSHOT.jar");
        File jarf = jar.toFile();
        if (jarf.exists() && jarf.isFile()) client.uploadJar(jarf);
        else throw new RuntimeException("File not found: " + jar.toString());
    }
}

2 个答案:

答案 0 :(得分:0)

要捕获TextInput的值,必须调用.on_change事件处理程序,为此,需要持久的Bokeh服务器连接。在下面的示例中,将显示test.csv文件的DataTable(几秒钟后),该文件位于TextInput中输入的文件夹名称(操作员名称)。输入操作员名称时,将调用my_text_input_handler()事件处理函数,并且new是更新后的值(或输入的值)。我们使用此变量的值替换您的代码中的user

注意:要运行此脚本,应将其保存到test.py之类的文件中,并使用bokeh serve --show test.py运行它。这将启动bokeh服务器连接。

from bokeh.layouts import widgetbox, gridplot
from bokeh.models import CustomJS, TextInput, Paragraph, DataTable, ColumnDataSource
from bokeh.plotting import curdoc
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
import os
import pandas as pd

welcome_message = 'Operator selected: (none)'

text_banner = Paragraph(text=welcome_message, width=200, height=100)

def callback_print(text_banner=text_banner):
    user_input = str(cb_obj.value)
    welcome_message =  'Operator selected: ' + user_input
    text_banner.text = welcome_message

def my_text_input_handler(attr, old, new):
    print("Previous label: " + old)
    print("Updated label: " + new)  
    basename = os.path.dirname(os.path.realpath('__file__')) 
    df = pd.read_csv(os.path.join(basename,str(new),'test.csv'), sep=",", na_filter =None)       
    Columns = [TableColumn(field=Ci, title=Ci, width=70) for Ci in df.columns]
    data_table = DataTable(columns=Columns, source=ColumnDataSource(df), width=1500)
    curdoc().add_root(gridplot([[data_table]], sizing_mode='scale_both'))

text_input = TextInput( title="Enter operator Name:",callback=CustomJS.from_py_func(callback_print))
text_input.on_change('value', my_text_input_handler)
curdoc().add_root(widgetbox(text_input, text_banner))

答案 1 :(得分:-1)

您可以从os模块中使用os.walk(),这将返回目录中的所有csv文件。

list_csv = []
def parse_csv(d):
    global list_csv
    for root,subdirs,files in os.walk(d):
        list_csv.extend([os.path.join(root,f) for f in files if '.csv' in f])
        for sd in subdirs:
            parse_csv(os.path.join(d,sd))

此外,如果这样做没有帮助,请您详细说明。