org.python.util.PythonInterpreter.eval()方法的使用及代码示例

x33g5p2x  于2022-01-26 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(216)

本文整理了Java中org.python.util.PythonInterpreter.eval()方法的一些代码示例,展示了PythonInterpreter.eval()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。PythonInterpreter.eval()方法的具体详情如下:
包路径:org.python.util.PythonInterpreter
类名称:PythonInterpreter
方法名:eval

PythonInterpreter.eval介绍

[英]Evaluates a string as a Python expression and returns the result.
[中]将字符串作为Python表达式求值并返回结果。

代码示例

代码示例来源:origin: nodebox/nodebox

Exception pythonException = null;
try {
  Object result = interpreter.eval(command);
  if (result != null) {
    addMessage(result.toString() + "\n");

代码示例来源:origin: com.sangupta/pepmint

/**
 * Create a new HTMLFormatter object using the given parameters.
 * 
 * @param params
 * @return
 */
public HtmlFormatter newHtmlFormatter(String params) {
  PyObject object = pythonInterpreter.eval("HtmlFormatter(" + params + ")");
  return new HtmlFormatter(object);
}

代码示例来源:origin: MarkusBernhardt/robotframework-selenium2library-java

protected File getLogDir() {
  if (logDir == null
      && !loggingPythonInterpreter.get().eval("EXECUTION_CONTEXTS.current").toString().equals("None")) {
    PyString logDirName = (PyString) loggingPythonInterpreter.get().eval(
        "BuiltIn().get_variables()['${LOG FILE}']");
    if (logDirName != null && !(logDirName.asString().toUpperCase().equals("NONE"))) {
      return new File(logDirName.asString()).getParentFile();
    }
    logDirName = (PyString) loggingPythonInterpreter.get().eval("BuiltIn().get_variables()['${OUTPUTDIR}']");
    return new File(logDirName.asString()).getParentFile();
  } else {
    return new File(logDir);
  }
}

代码示例来源:origin: org.fujion/fujion-script-jython

@Override
  public Object run(Map<String, Object> variables) {
    try (PythonInterpreter interp = new PythonInterpreter()) {
      if (variables != null) {
        for (Entry<String, Object> entry : variables.entrySet()) {
          interp.set(entry.getKey(), entry.getValue());
        }
      }
      return interp.eval(script);
    }
  }
}

代码示例来源:origin: org.carewebframework/org.carewebframework.web.script.jython

@Override
  public Object run(Map<String, Object> variables) {
    try (PythonInterpreter interp = new PythonInterpreter()) {
      if (variables != null) {
        for (Entry<String, Object> entry : variables.entrySet()) {
          interp.set(entry.getKey(), entry.getValue());
        }
      }
      return interp.eval(script);
    }
  }
}

代码示例来源:origin: stackoverflow.com

import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;

public class JavaProg
{
  static PythonInterpreter interpreter;

  @SuppressWarnings("resource")
public static void main( String gargs[] )
  {
   String[] s = {"New York", "Chicago"};
   PythonInterpreter.initialize(System.getProperties(),System.getProperties(), s);
   interpreter = new PythonInterpreter();
   interpreter.execfile("PyScript.py");
   PyInstance hello = (PyInstance) interpreter.eval("PyScript" + "(" + "None" + ")");
  }

  public void getData(Object[] data)
  {
    for (int i = 0; i < data.length; i++) {
      System.out.print(data[i].toString());
  }

  }
}

代码示例来源:origin: MarkusBernhardt/robotframework-selenium2library-java

public void runOnFailure() {
  if (runOnFailureKeyword == null) {
    return;
  }
  if (runningOnFailureRoutine) {
    return;
  }
  if(runOnFailurePythonInterpreter.get().eval("EXECUTION_CONTEXTS.current").toString().equals("None")) {
    return;
  }
  
  try {
    runOnFailurePythonInterpreter.get().exec(
        String.format("BIN.run_keyword('%s')",
            runOnFailureKeyword.replace("'", "\\'").replace("\n", "\\n")));
  } catch (RuntimeException r) {
    logging.warn(String.format("Keyword '%s' could not be run on failure%s", runOnFailureKeyword,
        r.getMessage() != null ? " '" + r.getMessage() + "'" : ""));
  } finally {
    runningOnFailureRoutine = false;
  }
}

代码示例来源:origin: stackoverflow.com

import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;

public class method {

public static void main(String[] args) {

  PythonInterpreter interpreter = new PythonInterpreter();
  interpreter.execfile("/pathtoyourmodule/somme_x_y.py");
  PyObject str = interpreter.eval("repr(somme(4,5))");
  System.out.println(str.toString());

}

代码示例来源:origin: org.jenkins-ci.plugins/python-wrapper

/**
 * Call the function inside Jython interpreter and return PyObject
 */
private PyObject execPythonGeneric(String function, Object ... params) {
  int myCallId = getCallId();
  // prepare function call string
  String paramName;
  String execStr = function + "(";
  for (int i = 0; i < params.length; i++) {
    paramName = "_" + function + "_" + (new Integer(myCallId)).toString() + "_" + (new Integer(i)).toString();
    pinterp.set(paramName, params[i]);
    execStr += paramName;
    if (i < params.length-1) {
      execStr += ", ";
    }
  }
  execStr += ")";
  // call function inside Jython interpreter
  PyObject obj = pinterp.eval(execStr);
  // delete params from Jython interpreter namespace
  for (int i = 0; i < params.length; i++) {
    paramName = "_" + function + "_" + (new Integer(myCallId)).toString() + "_" + (new Integer(i)).toString();
    pinterp.exec("del " + paramName);
  }
  return obj;
}

代码示例来源:origin: usc-isi-i2/Web-Karma

private boolean evaluatePythonExpression(Row r, PyCode code, PythonInterpreter interpreter) {
  evalColumns.clear();
  try {
    ArrayList<Node> nodes = new ArrayList<>(r.getNodes());
    Node node = nodes.get(0);
    interpreter.getLocals().__setitem__("nodeid", new PyString(node.getId()));
    PyObject output = interpreter.eval(code);
    return PythonTransformationHelper.getPyObjectValueAsBoolean(output);
  }catch(Exception e) {
    return onError;
  }
}

代码示例来源:origin: org.apache.apex/malhar-contrib

@Override
public void process(Map<String, Object> tuple)
{
 for (Map.Entry<String, Object> entry : tuple.entrySet()) {
  interp.set(entry.getKey(), entry.getValue());
 }
 evalResult = interp.eval(code);
 if (isPassThru) {
  if (result.isConnected()) {
   result.emit(evalResult);
  }
  if (outBindings.isConnected()) {
   outBindings.emit(new HashMap<String, Object>(getBindings()));
  }
 }
}

代码示例来源:origin: apache/apex-malhar

@Override
public void process(Map<String, Object> tuple)
{
 for (Map.Entry<String, Object> entry : tuple.entrySet()) {
  interp.set(entry.getKey(), entry.getValue());
 }
 evalResult = interp.eval(code);
 if (isPassThru) {
  if (result.isConnected()) {
   result.emit(evalResult);
  }
  if (outBindings.isConnected()) {
   outBindings.emit(new HashMap<String, Object>(getBindings()));
  }
 }
}

代码示例来源:origin: org.python/jython

/**
 * Show that a PythonInterpreter comes by default with a PlainConsole (not JLine say).
 */
public void testConsoleIsPlain() throws Exception {
  PythonInterpreter interp = new PythonInterpreter();
  interp.exec("import sys");
  Console console = Py.tojava(interp.eval("sys._jy_console"), Console.class);
  assertEquals(PlainConsole.class, console.getClass());
  Console console2 = Py.getConsole();
  assertEquals(PlainConsole.class, console2.getClass());
}

代码示例来源:origin: io.cloudslang/runtime-management-impl

protected Serializable eval(String prepareEnvironmentScript, String script) {
  if (interpreter.get(TRUE) == null) {
    interpreter.set(TRUE, Boolean.TRUE);
  }
  if (interpreter.get(FALSE) == null) {
    interpreter.set(FALSE, Boolean.FALSE);
  }
  if(prepareEnvironmentScript != null && !prepareEnvironmentScript.isEmpty()) {
    interpreter.exec(prepareEnvironmentScript);
  }
  PyObject evalResultAsPyObject = interpreter.eval(script);
  Serializable evalResult;
  evalResult = resolveJythonObjectToJavaEval(evalResultAsPyObject, script);
  return evalResult;
}

代码示例来源:origin: CloudSlang/score

protected Serializable eval(String prepareEnvironmentScript, String script) {
  if (interpreter.get(TRUE) == null) {
    interpreter.set(TRUE, Boolean.TRUE);
  }
  if (interpreter.get(FALSE) == null) {
    interpreter.set(FALSE, Boolean.FALSE);
  }
  if(prepareEnvironmentScript != null && !prepareEnvironmentScript.isEmpty()) {
    interpreter.exec(prepareEnvironmentScript);
  }
  PyObject evalResultAsPyObject = interpreter.eval(script);
  Serializable evalResult;
  evalResult = resolveJythonObjectToJavaEval(evalResultAsPyObject, script);
  return evalResult;
}

代码示例来源:origin: org.python/jython

/**
 * Motivated by a NPE reported on http://bugs.jython.org/issue1174.
 */
public void testBasicEval() throws Exception {
  PyDictionary test = new PyDictionary();
  test.__setitem__(new PyUnicode("one"), new PyUnicode("two"));
  PythonInterpreter.initialize(System.getProperties(), null, new String[] {});
  PythonInterpreter interp = new PythonInterpreter();
  PyObject pyo = interp.eval("{u'one': u'two'}");
  assertEquals(test, pyo);
}

代码示例来源:origin: scijava/scijava-jupyter-kernel

/**
   * @param args the command line arguments
   */
  public static void main(String[] args) throws PyException {

    PythonInterpreter interp = new PythonInterpreter();

    Object result = interp.eval(interp.compile("p=999\n555")).__tojava__(Object.class);
    System.out.println(result);

    interp = new PythonInterpreter();

    result = interp.eval(interp.compile("555")).__tojava__(Object.class);
    System.out.println(result);
    
  }
}

代码示例来源:origin: stackoverflow.com

PythonInterpreter py = new PythonInterpreter();
String dataFolder,prepFolder;
py.execfile("filename.py");
py.set("df", dataFolder);
py.set("pf", prepFolder);
py.exec("prep = Preprocess(df, pf)");

//if the preprocess method does not return anything, you can do:
py.exec("prep.preprocess()");

//To get the return value in java, you can do:
SomeJavaClass retvalue = py.eval("prep.preprocess()").__tojava__(SomeJavaClass.class);

//To get and store the return type in the python local namespace:
py.exec("retValue = prep.preprocess()");

代码示例来源:origin: org.python/jython

private Object eval(PyCode code, ScriptContext context) throws ScriptException {
  try {
    interp.setIn(context.getReader());
    interp.setOut(context.getWriter());
    interp.setErr(context.getErrorWriter());
    interp.setLocals(new PyScriptEngineScope(this, context));
    return interp.eval(code).__tojava__(Object.class);
  } catch (PyException pye) {
    throw scriptException(pye);
  }
}

代码示例来源:origin: usc-isi-i2/Web-Karma

PyObject returnVal = interpreter.eval(String.format("%s.getResult()", instanceName));
parentRow.getNode(newHNodeId).setValue(PythonTransformationHelper.getPyObjectValueAsString(returnVal), Node.NodeStatus.original, factory);

相关文章