Script python in java

hello, I am working on running a phynton code in a java sdk module, first I wanted to try with a simpler function as I show below and I manage to extract the date

protected void testImpl() throws Exception {
    GatewayContext context = GatewayHook.getGatewayContext();
    ScriptManager scriptManager = context.getScriptManager();

    PyStringMap a = scriptManager.createLocalsMap();

    try {
        scriptManager.runCode("a = system.date.now()", a, "");

        logger.info("a: " + a.values().get(0));

    }catch (JythonExecException e){
        e.printStackTrace();
    }
}

then, I wanted to try building a dataset but I haven't been able to get the code to work.

    ScriptManager scriptManager = context.getScriptManager();
    PyStringMap a = scriptManager.createLocalsMap();
    
    //String code = "ds11 = system.dataset.toDataSet(" + columnName + "," + dsData + ")";
    //String code = "a = system.dataset.toDataSet([a,b],[[12,12],[11,10]])";
    //logger.info("code: " + code);
    try {
        scriptManager.runCode("a = system.dataset.toDataSet([a,b],[[12,12],[11,10]])", a,"");
        logger.info("ds11: " + a);
        logger.info("ds11: " + a.values().get(0));
        
    }catch (JythonExecException e){
        e.printStackTrace();
    }

Why are you using this construct? Use the methods of PyStringMap to get by name. Probably this one, but note the warning. (Java string constants are automatically interned, fwiw.)

2 Likes

I'm using it for testing, but how would it be the way you mention?

a.__finditem__("a")

1 Like

ok, I understand, I was able to extract the date that way, however the dataset does not seem to be built.

Probably because your header names are non-existing variable names instead of strings.

Consider not using the same variable names for multiple purposes. It makes troubleshooting a nightmare.

3 Likes

correct, by changing the instruction to this I managed to build the dataset and it has solved my problem, thank you very much.

        scriptManager.runCode("ds11 = system.dataset.toDataSet(['a','b'],[[10,11],[12,13]])", stringMap,"");

Now I would like to take the opportunity to ask another question that has to do with the same thing, I have a historical query, which I receive in a List < String > the header and in a List <List< double >> the data, but I get an error when building the dataset, what could you recommend?

1 Like

Seems like you are trying to use java types in your python. Use Py.javaToPy() and Py.pyToJava() to move data back and forth.

And you really should not be using jython to build your datasets for java. Use the DatasetBuilder class directly.

Using ScriptManager.runCode() or .runFunction() have substantial overhead. Don't use jython in your module for anything that isn't user-supplied.

2 Likes