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);
@Override public void write(Kryo kryo, Output output, PyString object) { output.writeString(object.asString()); }
final private PyObject find_class(String module, String name) { if (find_global != null) { if (find_global == Py.None) throw new PyException(UnpicklingError, "Global and instance pickles are not supported."); return find_global.__call__(new PyString(module), new PyString(name)); } PyObject modules = Py.getSystemState().modules; PyObject mod = modules.__finditem__(module.intern()); if (mod == null) { mod = importModule(module); } PyObject global = mod.__findattr__(name.intern()); if (global == null) { throw new PyException(Py.SystemError, "Failed to import class " + name + " from module " + module); } return global; }
public static PyObject filterBaseString(PyObject func, PyBaseString seq, PyType stringType) { if (func == Py.None && seq.getType() == stringType) { // If it's a real string we can return the original, as no character is ever // false and __getitem__ does return this character. If it's a subclass we // must go through the __getitem__ loop return seq; } StringBuilder builder = new StringBuilder(); for (PyObject item : seq.asIterable()) { if (func == Py.None) { if (!item.__nonzero__()) { continue; } } else if (!func.__call__(item).__nonzero__()) { continue; } if (!Py.isInstance(item, stringType)) { String name = stringType.fastGetName(); throw Py.TypeError(String.format("can't filter %s to %s: __getitem__ returned " + "different type", name, name)); } builder.append(item.toString()); } String result = builder.toString(); return stringType == PyString.TYPE ? new PyString(result) : new PyUnicode(result); }
public static void classDictInit(PyObject dict) { dict.__setitem__("__name__", new PyString("_jythonlib")); dict.__setitem__("__doc__", __doc__); dict.__setitem__("__module__", new PyString("_jythonlib")); dict.__setitem__("dict_builder", dict_builder.TYPE); dict.__setitem__("set_builder", set_builder.TYPE); // Hide from Python dict.__setitem__("classDictInit", null); }
public static PyObject find_module(String name, PyObject path) { if (path == Py.None && PySystemState.getBuiltin(name) != null) { return new PyTuple(Py.None, Py.newString(name), new PyTuple(Py.EmptyString, Py.EmptyString, Py.newInteger(C_BUILTIN))); } if (path == Py.None) { path = Py.getSystemState().path; } for (PyObject p : path.asIterable()) { ModuleInfo mi = findFromSource(name, p.toString(), false, true); if(mi == null) { continue; } return new PyTuple(mi.file, new PyString(mi.filename), new PyTuple(new PyString(mi.suffix), new PyString(mi.mode), Py.newInteger(mi.type))); } throw Py.ImportError("No module named " + name); }
static PyObject loadFromLoader(PyObject importer, String name) { PyUnicode.checkEncoding(name); PyObject load_module = importer.__getattr__("load_module"); ReentrantLock importLock = Py.getSystemState().getImportLock(); importLock.lock(); try { return load_module.__call__(new PyObject[]{new PyString(name)}); } finally { importLock.unlock(); } }
public PyTuple lookup(String encoding) { PyString v = new PyString(normalizestring(encoding)); PyObject cached = searchCache.__finditem__(v); if (cached != null) { return (PyTuple)cached; } if (searchPath.__len__() == 0) { throw new PyException(Py.LookupError, "no codec search functions registered: can't find encoding '" + encoding + "'"); } for (PyObject func : searchPath.asIterable()) { PyObject created = func.__call__(v); if (created == Py.None) { continue; } if (!(created instanceof PyTuple) || created.__len__() != 4) { throw Py.TypeError("codec search functions must return 4-tuples"); } searchCache.__setitem__(v, created); return (PyTuple)created; } throw new PyException(Py.LookupError, "unknown encoding '" + encoding + "'"); }
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(); } });
@ExposedMethod final void instance___setattr__(String name, PyObject value) { if (name == "__class__") { if (value instanceof PyClass) { instclass = (PyClass) value; if (instclass.__del__ != null && !JyAttribute.hasAttr(this, JyAttribute.FINALIZE_TRIGGER_ATTR)) { FinalizeTrigger.ensureFinalizer(this); } } else { throw Py.TypeError("__class__ must be set to a class"); } return; } else if (name == "__dict__") { __dict__ = value; return; } PyObject setter = instclass.__setattr__; if (setter != null) { setter.__call__(this, new PyString(name), value); } else { __dict__.__setitem__(name, value); } if (name == "__del__" && !JyAttribute.hasAttr(this, JyAttribute.FINALIZE_TRIGGER_ATTR)) { FinalizeTrigger.ensureFinalizer(this); } }
private PyCode getCompiledCode(String pythonCode, PythonInterpreter interpreter, String selectionId) throws IOException { final ServletContextParameterMap contextParameters = ContextParametersRegistry.getInstance().getContextParameters(workspace.getContextId()); String trimmedSelectionCode = pythonCode.trim(); Worksheet worksheet = workspace.getWorksheet(worksheetId); if (trimmedSelectionCode.isEmpty()) { trimmedSelectionCode = "return False"; } String selectionMethodStmt = PythonTransformationHelper .getPythonSelectionMethodDefinitionState(worksheet, trimmedSelectionCode, selectionId); logger.debug("Executing PySelection\n" + selectionMethodStmt); // Prepare the Python interpreter PythonRepository repo = PythonRepositoryRegistry.getInstance().getPythonRepository(contextParameters.getParameterValue(ContextParameter.USER_PYTHON_SCRIPTS_DIRECTORY)); repo.compileAndAddToRepositoryAndExec(interpreter, selectionMethodStmt); PyObject locals = interpreter.getLocals(); locals.__setitem__("workspaceid", new PyString(workspace.getId())); locals.__setitem__("selectionName", new PyString(superSelectionName)); locals.__setitem__("command", Py.java2py(this)); locals.__setitem__("worksheetId", new PyString(worksheetId)); return repo.getSelectionCode(); }
@ExposedMethod final void instance___delattr__(String name) { PyObject deller = instclass.__delattr__; if (deller != null) { deller.__call__(this, new PyString(name)); } else { try { __dict__.__delitem__(name); } catch (PyException exc) { if (exc.match(Py.KeyError)) throw Py.AttributeError("class " + instclass.__name__ + " has no attribute '" + name + "'"); } ; } }
public synchronized static void initializePython() { if (isInitialized.get()) return; // Set the Jython package cache directory. Properties jythonProperties = new Properties(); String jythonCacheDir = Platform.getUserDataDirectory() + Platform.SEP + "_jythoncache"; jythonProperties.put("python.cachedir", jythonCacheDir); // Initialize Python. PySystemState.initialize(System.getProperties(), jythonProperties, new String[]{""}); // Add the built-in Python libraries. File nodeBoxLibraries = new File(libDir, "nodeboxlibs.zip"); Py.getSystemState().path.add(new PyString(nodeBoxLibraries.getAbsolutePath())); // This folder contains unarchived NodeBox libraries. // Only used in development. File developmentLibraries = new File("src/main/python"); Py.getSystemState().path.add(new PyString(developmentLibraries.getAbsolutePath())); // Add the user's Python directory. Py.getSystemState().path.add(new PyString(Platform.getUserPythonDirectory().getAbsolutePath())); isInitialized.set(true); }
/** * If a class doesn't define a __repr__ method of its own, the return * value from this method is used. */ protected PyString makeDefaultRepr() { PyObject mod = instclass.__dict__.__finditem__("__module__"); String modStr = (mod == null || !Py.isInstance(mod, PyString.TYPE)) ? "?" : mod.toString(); return new PyString(String.format("<%s.%s instance at %s>", modStr, instclass.__name__, Py.idstr(this))); }
private TraceFunction safeCall(PyFrame frame, String label, PyObject arg) { synchronized(imp.class) { synchronized(this) { ThreadState ts = Py.getThreadState(); if(ts.tracing) return null; if(tracefunc == null) return null; PyObject ret = null; try { ts.tracing = true; ret = tracefunc.__call__(frame, new PyString(label), arg); } catch(PyException exc) { frame.tracefunc = null; ts.tracefunc = null; ts.profilefunc = null; throw exc; } finally { ts.tracing = false; } if(ret == tracefunc) return this; if(ret == Py.None) return null; return new PythonTraceFunction(ret); } } }
private void module___init__(PyObject name, PyObject doc) { ensureDict(); __dict__.__setitem__("__name__", name); __dict__.__setitem__("__doc__", doc); if (name.equals(new PyString("__main__"))) { __dict__.__setitem__("__builtins__", Py.getSystemState().modules.__finditem__("__builtin__")); __dict__.__setitem__("__package__", Py.None); } }
/** * Return a string containing the values v1, v2, ... packed according * to the given format. The arguments must match the * values required by the format exactly. */ static public PyString pack(PyObject[] args) { if (args.length < 1) Py.TypeError("illegal argument type for built-in operation"); String format = args[0].toString(); FormatDef[] f = whichtable(format); int size = calcsize(format, f); return new PyString(pack(format, f, size, 1, args).toString()); }