org.python.util.PythonInterpreter类的使用及代码示例

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

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

PythonInterpreter介绍

[英]The PythonInterpreter class is a standard wrapper for a Jython interpreter for embedding in a Java application.
[中]PythonInterpreter类是嵌入Java应用程序的Jython解释器的标准包装器。

代码示例

代码示例来源:origin: Raysmond/SpringBlog

@Override
  public String highlight(String content) {
    PythonInterpreter interpreter = new PythonInterpreter();

    // Set a variable with the content you want to work with
    interpreter.set("code", content);

    // Simple use Pygments as you would in Python
    interpreter.exec("from pygments import highlight\n"
        + "from pygments.lexers import PythonLexer\n"
        + "from pygments.formatters import HtmlFormatter\n"
        + "\nresult = highlight(code, PythonLexer(), HtmlFormatter())");

    return interpreter.get("result", String.class);
  }
}

代码示例来源:origin: spring-projects/spring-security

public boolean before(Authentication authentication, MethodInvocation mi,
    PreInvocationAttribute preAttr) {
  PythonInterpreterPreInvocationAttribute pythonAttr = (PythonInterpreterPreInvocationAttribute) preAttr;
  String script = pythonAttr.getScript();
  PythonInterpreter python = new PythonInterpreter();
  python.set("authentication", authentication);
  python.set("args", createArgumentMap(mi));
  python.set("method", mi.getMethod().getName());
  Resource scriptResource = new PathMatchingResourcePatternResolver()
      .getResource(script);
  try {
    python.execfile(scriptResource.getInputStream());
  }
  catch (IOException e) {
    throw new IllegalArgumentException("Couldn't run python script, " + script, e);
  }
  PyObject allowed = python.get("allow");
  if (allowed == null) {
    throw new IllegalStateException("Python script did not set the permit flag");
  }
  return (Boolean) Py.tojava(allowed, Boolean.class);
}

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

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModiles if they're not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);

代码示例来源:origin: apache/flink

private static synchronized PythonInterpreter initPythonInterpreter(String[] args, String pythonPath, String scriptName) {
    if (!jythonInitialized) {
      // the java stack traces within the jython runtime aren't useful for users
      System.getProperties().put("python.options.includeJavaStackInExceptions", "false");
      PySystemState.initialize(System.getProperties(), new Properties(), args);

      pythonInterpreter = new PythonInterpreter();

      pythonInterpreter.getSystemState().path.add(0, pythonPath);

      pythonInterpreter.setErr(System.err);
      pythonInterpreter.setOut(System.out);

      pythonInterpreter.exec("import " + scriptName);
      jythonInitialized = true;
    }
    return pythonInterpreter;
  }
}

代码示例来源:origin: org.jvnet.hudson.plugins/jython

public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener)  throws IOException, InterruptedException {
    PySystemState sys = new PySystemState();
    sys.setCurrentWorkingDir(build.getWorkspace().getRemote());
    PythonInterpreter interp = new PythonInterpreter(null, sys);

    interp.setOut(listener.getLogger());
    interp.setErr(listener.getLogger());
    interp.exec(this.getCommand());
    interp.cleanup();

    build.setResult(Result.SUCCESS);
    return true;
  }
}

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

public void testMod() {
    interp.exec("c = b % a");
    assertEquals(new PyLong(4000000000L), interp.get("c"));
  }
}

代码示例来源:origin: org.freemarker/freemarker

private PythonInterpreter createInterpreter(Map vars) {
  PythonInterpreter pi = new PythonInterpreter();
  Iterator it = vars.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry ent = (Map.Entry) it.next(); 
    pi.set((String) ent.getKey(), ent.getValue());
  }
  return pi;
}

代码示例来源: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: 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.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: stackoverflow.com

import org.python.util.PythonInterpreter;

public class FirstJavaScript {

  public static void main(String args[]) {
     PythonInterpreter interpreter = new PythonInterpreter();
     interpreter.execfile("/home/XXX/XXX/test.py");
  }
}

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

PythonInterpreter interp = new PythonInterpreter();
 interp.set("a", this);
 interp.exec("import externalscript");
 interp.exec("externalscript.function(a)");

代码示例来源:origin: com.googlecode.the-fascinator.plugins/plugin-indexer-solr

/**
 * Evaluate and return a Python script.
 * 
 * @param inStream : InputStream containing the script to evaluate
 * @param scriptName : filename of the script (mainly for debugging)
 * @return PyObject : Compiled result
 */
private PyObject evalScript(InputStream inStream, String scriptName) {
  // Execute the script
  PythonInterpreter python = new PythonInterpreter();
  python.execfile(inStream, scriptName);
  // Get the result and cleanup
  PyObject scriptClass = python.get(SCRIPT_CLASS_NAME);
  python.cleanup();
  // Instantiate and return the result
  return scriptClass.__call__();
}

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

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

public class SimpleEmbedded { 
  public static void main(String[] args) throws PyException {
    PythonInterpreter interp = new PythonInterpreter();
    interp.exec("nums = [1,2,3]");
    PyObject nums = interp.get("nums");
    System.out.println("nums: " + nums);
    System.out.println("nums is of type: " + nums.getClass());
  }
}

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

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
interpreter.setOut(outputStream);
interpreter.setErr(errorStream);
interpreter.set("document", document);
interpreter.set("root", document.getNodeLibrary().getRoot());
interpreter.set("parent", document.getActiveNetwork());
interpreter.set("node", document.getActiveNode());
interpreter.exec("from nodebox.node import *");
Exception pythonException = null;
try {
  Object result = interpreter.eval(command);
  if (result != null) {
    addMessage(result.toString() + "\n");

代码示例来源: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: apache/flink

/**
 * Initializes the Jython interpreter and executes a python script.
 *
 * @param factory environment factory
 * @param scriptDirectory the directory containing all required user python scripts
 * @param scriptName the name of the main python script
 * @param args Command line arguments that will be delivered to the executed python script
 */
public static void initAndExecPythonScript(PythonEnvironmentFactory factory, java.nio.file.Path scriptDirectory, String scriptName, String[] args) {
  String[] fullArgs = new String[args.length + 1];
  fullArgs[0] = scriptDirectory.resolve(scriptName).toString();
  System.arraycopy(args, 0, fullArgs, 1, args.length);
  PythonInterpreter pythonInterpreter = initPythonInterpreter(fullArgs, scriptDirectory.toUri().getPath(), scriptName);
  pythonInterpreter.set("__flink_env_factory__", factory);
  pythonInterpreter.exec(scriptName + ".main(__flink_env_factory__)");
}

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

public ImmutableMap<String, Function> call() throws Exception {
    // This creates a dependency between function and the client.
    // However, we need to know the load paths before we can do anything, so this is necessary.
    PythonUtils.initializePython();
    Py.getSystemState().path.append(new PyString(file.getParentFile().getCanonicalPath()));
    PythonInterpreter interpreter = new PythonInterpreter();
    try {
      interpreter.execfile(file.getCanonicalPath());
    } catch (IOException e) {
      throw new LoadException(file, e);
    } catch (PyException e) {
      throw new LoadException(file, e);
    }
    PyStringMap map = (PyStringMap) interpreter.getLocals();
    ImmutableMap.Builder<String, Function> builder = ImmutableMap.builder();
    for (Object key : map.keys()) {
      Object o = map.get(Py.java2py(key));
      if (o instanceof PyFunction) {
        String name = (String) key;
        Function f = new PythonFunction(name, (PyFunction) o);
        builder.put(name, f);
      }
    }
    return builder.build();
  }
});

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

interp.exec("import io\n" + //
    "u = u'" + escapedText + "'\n" +    //
    "b = b'" + escapedText + "'\n"      //
interp.exec("f = open('" + F + "', 'wb', 0)");
PyFile pyf = (PyFile)interp.get("f");
assertNotNull(pyf);
RawIOBase r = (RawIOBase)pyf.fileno().__tojava__(RawIOBase.class);
interp.exec("fb = open('" + FB + "', 'wb')");
PyFile pyfb = (PyFile)interp.get("fb");
assertNotNull(pyfb);
RawIOBase rb = (RawIOBase)pyfb.fileno().__tojava__(RawIOBase.class);
interp.exec("ft = open('" + FT + "', 'w')");
PyFile pyft = (PyFile)interp.get("ft");
assertNotNull(pyft);
RawIOBase rt = (RawIOBase)pyft.fileno().__tojava__(RawIOBase.class);
interp.exec("f.write(b)");
interp.exec("fb.write(b)");
interp.exec("ft.write(u)");
interp.cleanup();

代码示例来源:origin: org.twdata.enchanter/enchanter-python

public static void main(String[] args) throws IOException {
  ScriptRecorder rec = new PythonScriptRecorder();
  
  args = rec.processForLearningMode(args);
  String filePath = args[0];
  PythonInterpreter interp = new PythonInterpreter();
  StreamConnection conn = new DefaultStreamConnection();
  
  // deprecated
  interp.set("ssh", conn);
  interp.set("conn", conn);
  interp.set("args", args);
  interp.execfile(filePath);
  
}

相关文章