Java Code Examples for org.python.core.PyList#add()

The following examples show how to use org.python.core.PyList#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JythonUtils.java    From spork with Apache License 2.0 6 votes vote down vote up
public static PyObject pigToPython(Object object) {
    if (object instanceof Tuple) {
        return pigTupleToPyTuple((Tuple) object);
    } else if (object instanceof DataBag) {
        PyList list = new PyList();
        for (Tuple bagTuple : (DataBag) object) {
            list.add(pigTupleToPyTuple(bagTuple));
        }
        return list;
    } else if (object instanceof Map<?, ?>) {
        PyDictionary newMap = new PyDictionary();
        for (Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
            newMap.put(entry.getKey(), pigToPython(entry.getValue()));
        }
        return newMap;
    } else if (object instanceof DataByteArray) {
        return Py.java2py(((DataByteArray) object).get());
    } else {
        return Py.java2py(object);
    }
}
 
Example 2
Source File: JythonSupport.java    From SikuliX1 with MIT License 5 votes vote down vote up
public void setSysArgv(List<String> args) {
  if (null == interpreter) {
    return;
  }
  try {
    PyList pyArgv = interpreter.getSystemState().argv;
    pyArgv.clear();
    for (String arg : args) {
      pyArgv.add(arg);
    }
  } catch (Exception ex) {
    sysArgv = null;
  }
}
 
Example 3
Source File: JythonScriptSupport.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** @param path Path to add to head of python search path */
private void addToPythonPath(final String path)
{
    // Since using default PySystemState (see above), check if already in paths
    final PyList paths = python.getSystemState().path;

    // Prevent concurrent modification
    synchronized (JythonScriptSupport.class)
    {
        final int index = paths.indexOf(path);

        // Warn about "examples:/... path that won't really work.
        // Still add to the list so we only get the warning once,
        // plus maybe some day we'll be able to use it...
        if (index < 0  &&
            path.startsWith(ModelResourceUtil.EXAMPLES_SCHEMA + ":"))
            logger.log(Level.WARNING, "Jython will be unable to access scripts in " + path + ". Install examples in file system.");

        // Already top entry?
        if (index == 0)
            return;
        // Remove if further down in the list
        if (index > 0)
            paths.remove(index);
        // Add to front of list
        paths.add(0, path);
    }
    logger.log(Level.FINE, "Adding to jython path: {0}", path);
}
 
Example 4
Source File: JythonProcessor.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public Object createArray(List elements) {
  PyList list = new PyList();
  for (Object element : elements) {
    list.add(element);
  }
  return list;
}
 
Example 5
Source File: JIntrospect.java    From MeteoInfo with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Get auto complete list
 *
 * @param command The command
 * @param includeMagic
 * @param includeSingle
 * @param includeDouble
 * @return Auto complete list
 * @throws java.io.IOException
 */
public List<String> getAutoCompleteList(String command, boolean includeMagic,
        boolean includeSingle, boolean includeDouble) throws IOException {
    // Temp KLUDGE here rather than in console.py
    //command += ".";
    if (command.startsWith("import ") || command.startsWith("from ")) {
        String target = getPackageName(command);
        if (target == null) {
            return null;
        }
        return completePackageName(target);
    }
    
    String root = this.getRoot(command, ".");
    if (root.isEmpty())
        return null;
    
    try {
        PyObject object = this.interp.eval(root);
        PyList plist = (PyList) object.__dir__();
        if (plist.contains("__all__")) {
            PyList nPlist = (PyList) object.__getattr__("__all__");
            for (int i = 0; i < nPlist.__len__(); i++) {
                if (! plist.__contains__(nPlist.__getitem__(i))) {
                    plist.add(nPlist.__getitem__(i));
                }
            }
        }
        List<String> list = new ArrayList<>();
        String name;
        for (int i = 0; i < plist.__len__(); i++) {
            name = plist.get(i).toString();
            if (!name.contains("__")) {
                list.add(name);
            }
        }
        return list;
    } catch (Exception e){
        return null;
    }
}
 
Example 6
Source File: FlightTelemetry.java    From hazelcast-jet-demos with Apache License 2.0 4 votes vote down vote up
PyList getAsList() {
    PyList list = new PyList();
    PyTuple metric = new PyTuple(metricName, new PyTuple(timestamp, metricValue));
    list.add(metric);
    return list;
}
 
Example 7
Source File: JythonScriptSupport.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
/** Perform static, one-time initialization */
private static boolean init()
{
    try
    {
        final Properties pre_props = System.getProperties();
        final Properties props = new Properties();

        // Jython 2.7(b3) needed these to set sys.prefix and sys.executable.
        // Locate the jython plugin for 'home' to allow use of /Lib in there
        // final String home = null; // getPluginPath("org.python.jython", "/");

        // If left undefined, initialization of Lib/site.py fails with
        // posixpath.py", line 394, in normpath AttributeError:
        // 'NoneType' object has no attribute 'startswith'
        // props.setProperty("python.home", home);
        // props.setProperty("python.executable", "None");

        // Disable cachedir to avoid creation of cachedir folder.
        // See http://www.jython.org/jythonbook/en/1.0/ModulesPackages.html#java-package-scanning
        // and http://wiki.python.org/jython/PackageScanning
        props.setProperty(RegistryKey.PYTHON_CACHEDIR_SKIP, "true");

        // By default, Jython compiler creates bytecode files xxx$py.class
        // adjacent to the *.py source file.
        // They are owned by the current user, which typically results in
        // problems for other users, who can either not read them, or not
        // write updates after *.py changes.
        // There is no way to have them be created in a different, per-user directory.
        // C Python honors an environment variable PYTHONDONTWRITEBYTECODE=true to
        // disable its bytecode files, but Jython only checks that in its command line launcher.
        // Use the same environment variable in case it's defined,
        // and default to disabled bytecode, i.e. the safe alternative.
        if (System.getenv("PYTHONDONTWRITEBYTECODE") == null)
            Options.dont_write_bytecode = true;
        else
            Options.dont_write_bytecode = Boolean.parseBoolean(System.getenv("PYTHONDONTWRITEBYTECODE"));

        // With python.home defined, there is no more
        // "ImportError: Cannot import site module and its dependencies: No module named site"
        // Skipping the site import still results in faster startup
        props.setProperty("python.import.site", "false");

        // Prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
        props.setProperty("python.console.encoding", "UTF-8");

        // This will replace entries found on JYTHONPATH
        final String python_path = Preferences.python_path;
        if (! python_path.isEmpty())
            props.setProperty("python.path", python_path);

        // Options: error, warning, message (default), comment, debug
        // props.setProperty("python.verbose", "debug");
        // org.python.core.Options.verbose = Py.DEBUG;

        PythonInterpreter.initialize(pre_props, props, new String[0]);
        final PySystemState state = Py.getSystemState();
        final PyList paths = state.path;

        // Add the examples/connect2j to path.
        // During development, examples are in
        // "file:/some/path/phoebus/applications/display/model/target/classes/examples"
        final String examples = ModelPlugin.class.getResource("/examples").toString();
        if (examples.startsWith("file:"))
            paths.add(examples.substring(5) + "/connect2j");
        // In the compiled version, examples are in
        // "jar:file:/some/path/display-model-0.0.1.jar!/examples"
        else if (examples.startsWith("jar:file:"))
            paths.add(examples.substring(9).replace("jar!/", "jar/") + "/connect2j");
        else
            logger.log(Level.WARNING, "Cannot locate examples/connect2j from " + examples);

        final PyVersionInfo version = PySystemState.version_info;
        logger.log(Level.INFO, "Initial Paths for Jython " + version.major + "." + version.minor + "." + version.micro + ": " + paths);

        // Scripts would sometimes fail in "from ... import ..." with this error:
        //
        // File "..jython-standalone-2.7.1.jar/Lib/warnings.py", line 226, in warn
        // IndexError: index out of range: 0
        //
        // That version of Lib/warnings.py:226 tries to read sys.argv[0],
        // so setting sys.argv[0] avoids the crash.
        // Since state is shared by all scripts in a display,
        // set it to a generic "DisplayBuilderScript"
        state.argv.clear();
        state.argv.add("DisplayBuilderScript");

        return true;
    }
    catch (Exception ex)
    {
        logger.log(Level.SEVERE, "Once this worked OK, but now the Jython initialization failed. Don't you hate computers?", ex);
    }
    return false;
}