Beispiel #1
0
def startJVM(jvm, *args):
    """
    Starts a Java Virtual Machine

    :param jvm:  Path to the jvm library file (libjvm.so, jvm.dll, ...)
    :param args: Arguments to give to the JVM
    """
    # Insert OS specific arguments first
    finder = get_jvm_finder()
    args = finder.normalize_arguments(jvm, list(args))

    # Start the JVM
    _jpype.startup(jvm, tuple(args), True)

    # Initialize jPype
    _jclass._initialize()
    _jarray._initialize()
    _jwrapper._initialize()
    _jproxy._initialize()
    _jexception._initialize()
    _jcollection._initialize()
    _jobject._initialize()
    _properties._initialize()
    nio._initialize()
    reflect._initialize()

    # start the reference daemon thread
    if _usePythonThreadForDaemon:
        _refdaemon.startPython()
    else:
        _refdaemon.startJava()
Beispiel #2
0
def startJVM(jvm, *args):
    """
    Starts a Java Virtual Machine

    :param jvm:  Path to the jvm library file (libjvm.so, jvm.dll, ...)
    :param args: Arguments to give to the JVM
    """
    # Insert OS specific arguments first
    finder = get_jvm_finder()
    args = finder.normalize_arguments(jvm, list(args))

    # Start the JVM
    _jpype.startup(jvm, tuple(args), True)

    # Initialize jPype
    _jclass._initialize()
    _jarray._initialize()
    _jwrapper._initialize()
    _jproxy._initialize()
    _jexception._initialize()
    _jcollection._initialize()
    _jobject._initialize()
    _properties._initialize()
    nio._initialize()
    reflect._initialize()

    # start the reference daemon thread
    if _usePythonThreadForDaemon:
        _refdaemon.startPython()
    else:
        _refdaemon.startJava()
Beispiel #3
0
 def testStartupBadArg(self):
     with self.assertRaisesRegex(TypeError, "4 arguments"):
         _jpype.startup()
     with self.assertRaisesRegex(TypeError, "must be tuple"):
         _jpype.startup(object(), object(), True, True)
     with self.assertRaisesRegex(TypeError, "must be strings"):
         _jpype.startup("", (object(), ), True, True)
     with self.assertRaisesRegex(TypeError, "must be a string"):
         _jpype.startup(object(), tuple(), True, True)
     with self.assertRaisesRegex(OSError, "started"):
         _jpype.startup("", tuple(), True, True)
Beispiel #4
0
def startJVM(jvm, *args):
    """
    Starts a Java Virtual Machine

    :param jvm:  Path to the jvm library file (libjvm.so, jvm.dll, ...)
    :param args: Arguments to give to the JVM
    """
    _jpype.startup(jvm, tuple(args), True)
    _initialize()

    # start the reference daemon thread
    if _usePythonThreadForDaemon:
        _refdaemon.startPython()
    else:
        _refdaemon.startJava()
Beispiel #5
0
def startJVM(jvm, *args) :
    _jpype.startup(jvm, tuple(args), True)
    _jclass._initialize()
    _jarray._initialize()
    _jwrapper._initialize()
    _jproxy._initialize()
    _jexception._initialize()
    _jcollection._initialize()
    _jobject._initialize()
    _properties._initialize()
    nio._initialize()
    reflect._initialize()

    # start the reference deamon thread
    if _usePythonThreadForDaemon :
        _refdaemon.startPython()
    else:
        _refdaemon.startJava()
Beispiel #6
0
def startJVM(jvm, *args):
    _jpype.startup(jvm, tuple(args), True)
    _jclass._initialize()
    _jarray._initialize()
    _jwrapper._initialize()
    _jproxy._initialize()
    _jexception._initialize()
    _jcollection._initialize()
    _jobject._initialize()
    _properties._initialize()
    nio._initialize()
    reflect._initialize()

    # start the reference deamon thread
    if _usePythonThreadForDaemon:
        _refdaemon.startPython()
    else:
        _refdaemon.startJava()
Beispiel #7
0
def startJVM(jvm=None, *args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvm.  The default classpath
    will be determined by jpype.getClassPath().  The default JVM is 
    determined by jpype.getDefaultJVMPath().

    Args:
      jvm (str):  Path to the jvm library file (libjvm.so, jvm.dll, ...)
        default=None will use jpype.getDefaultJVMPath()
      *args (str[]): Arguments to give to the JVM
      classpath (Optional[string]): set the classpath for the jvm.
        This will override any classpath supplied in the arguments
        list.
      ignoreUnrecognized (Optional[bool]): option to jvm to ignore
        invalid jvm arguments.  (Default False)
    """
    if jvm is None:
        jvm = get_default_jvm_path()

        # Check to see that the user has not set the classpath
        # Otherwise use the default if not specified
        if not _hasClassPath(args) and 'classpath' not in kwargs:
            kwargs['classpath'] = _classpath.getClassPath()
            print("Use default classpath")

    if 'ignoreUnrecognized' not in kwargs:
        kwargs['ignoreUnrecognized'] = False

    # Classpath handling
    args = list(args)
    if 'classpath' in kwargs and kwargs['classpath'] != None:
        args.append('-Djava.class.path=%s' % (kwargs['classpath']))
        print("Set classpath")

    if not isJVMStarted():
        _jpype.startup(jvm, tuple(args), kwargs['ignoreUnrecognized'])
    _initialize()

    # start the reference daemon thread
    if _usePythonThreadForDaemon:
        _refdaemon.startPython()
    else:
        _refdaemon.startJava()
Beispiel #8
0
def startJVM(jvm=None, *args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvm.  The default classpath
    will be determined by jpype.getClassPath().  The default JVM is 
    determined by jpype.getDefaultJVMPath().

    Args:
      jvm (str):  Path to the jvm library file (libjvm.so, jvm.dll, ...)
        default=None will use jpype.getDefaultJVMPath()
      *args (str[]): Arguments to give to the JVM
      classpath (Optional[string]): set the classpath for the jvm.
        This will override any classpath supplied in the arguments
        list.
      ignoreUnrecognized (Optional[bool]): option to jvm to ignore
        invalid jvm arguments.  (Default False)
    """
    if jvm is None:
        jvm = get_default_jvm_path()

        # Check to see that the user has not set the classpath
        # Otherwise use the default if not specified
        if not _hasClassPath(args) and 'classpath' not in kwargs:
           kwargs['classpath']=_classpath.getClassPath()
           print("Use default classpath")

    if 'ignoreUnrecognized' not in kwargs:
        kwargs['ignoreUnrecognized']=False

    # Classpath handling
    args = list(args)
    if 'classpath' in kwargs and kwargs['classpath']!=None:
        args.append('-Djava.class.path=%s'%(kwargs['classpath']))
        print("Set classpath")

    _jpype.startup(jvm, tuple(args), kwargs['ignoreUnrecognized'])
    _initialize()

    # start the reference daemon thread
    if _usePythonThreadForDaemon:
        _refdaemon.startPython()
    else:
        _refdaemon.startJava()
Beispiel #9
0
def startJVM(jvm, *args):
    """
    Starts a Java Virtual Machine

    :param jvm:  Path to the jvm library file (libjvm.so, jvm.dll, ...)
    :param args: Arguments to give to the JVM
    """
    _jpype.startup(jvm, tuple(args), True)
    _jclass._initialize()
    _jarray._initialize()
    _jwrapper._initialize()
    _jproxy._initialize()
    _jexception._initialize()
    _jcollection._initialize()
    _jobject._initialize()
    _properties._initialize()
    nio._initialize()
    reflect._initialize()

    # start the reference daemon thread
    if _usePythonThreadForDaemon:
        _refdaemon.startPython()
    else:
        _refdaemon.startJava()
Beispiel #10
0
def startJVM(jvm, *args):
    """
    Starts a Java Virtual Machine

    :param jvm:  Path to the jvm library file (libjvm.so, jvm.dll, ...)
    :param args: Arguments to give to the JVM
    """
    _jpype.startup(jvm, tuple(args), True)
    _jclass._initialize()
    _jarray._initialize()
    _jwrapper._initialize()
    _jproxy._initialize()
    _jexception._initialize()
    _jcollection._initialize()
    _jobject._initialize()
    _properties._initialize()
    nio._initialize()
    reflect._initialize()

    # start the reference daemon thread
    if _usePythonThreadForDaemon:
        _refdaemon.startPython()
    else:
        _refdaemon.startJava()
Beispiel #11
0
 def testStartup(self):
     _jpype.fault("PyJPModule_startup")
     with self.assertRaisesRegex(SystemError, "fault"):
         _jpype.startup()
Beispiel #12
0
def startJVM(*args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvmpath.

    The default classpath is determined by ``jpype.getClassPath()``.
    The default jvmpath is determined by ``jpype.getDefaultJVMPath()``.

    Parameters:
     *args (Optional, str[]): Arguments to give to the JVM.
        The first argument may be the path the JVM.

    Keyword Arguments:
      jvmpath (str):  Path to the jvm library file,
        Typically one of (``libjvm.so``, ``jvm.dll``, ...)
        Using None will apply the default jvmpath.
      classpath (str,[str]): Set the classpath for the JVM.
        This will override any classpath supplied in the arguments
        list. A value of None will give no classpath to JVM.
      ignoreUnrecognized (bool): Option to ignore
        invalid JVM arguments. Default is False.
      convertStrings (bool): Option to force Java strings to
        cast to Python strings. This option is to support legacy code
        for which conversion of Python strings was the default. This
        will globally change the behavior of all calls using
        strings, and a value of True is NOT recommended for newly
        developed code.
      interrupt (bool): Option to install ^C signal handlers.
        If True then ^C will stop the process, else ^C will
        transfer control to Python rather than halting.  If
        not specified will be False if Python is started as
        an interactive shell.

    Raises:
      OSError: if the JVM cannot be started or is already running.
      TypeError: if an invalid keyword argument is supplied
        or a keyword argument conflicts with the arguments.

     """
    if _jpype.isStarted():
        raise OSError('JVM is already started')
    global _JVM_started
    if _JVM_started:
        raise OSError('JVM cannot be restarted')

    args = list(args)

    # JVM path
    jvmpath = None
    if args:
        # jvm is the first argument the first argument is a path or None
        if not args[0] or not args[0].startswith('-'):
            jvmpath = args.pop(0)
    if 'jvmpath' in kwargs:
        if jvmpath:
            raise TypeError('jvmpath specified twice')
        jvmpath = kwargs.pop('jvmpath')
    if not jvmpath:
        jvmpath = getDefaultJVMPath()

    # Classpath handling
    if _hasClassPath(args):
        # Old style, specified in the arguments
        if 'classpath' in kwargs:
            # Cannot apply both styles, conflict
            raise TypeError('classpath specified twice')
        classpath = None
    elif 'classpath' in kwargs:
        # New style, as a keywork
        classpath = kwargs.pop('classpath')
    else:
        # Not speficied at all, use the default classpath
        classpath = _classpath.getClassPath()

    # Handle strings and list of strings.
    if classpath:
        if isinstance(classpath, str):
            args.append('-Djava.class.path=%s' % _handleClassPath([classpath]))
        elif hasattr(classpath, '__iter__'):
            args.append('-Djava.class.path=%s' % _handleClassPath(classpath))
        else:
            raise TypeError("Unknown class path element")

    ignoreUnrecognized = kwargs.pop('ignoreUnrecognized', False)
    convertStrings = kwargs.pop('convertStrings', False)
    interrupt = kwargs.pop('interrupt', not interactive())

    if kwargs:
        raise TypeError("startJVM() got an unexpected keyword argument '%s'" %
                        (','.join([str(i) for i in kwargs])))

    try:
        _jpype.startup(jvmpath, tuple(args), ignoreUnrecognized,
                       convertStrings, interrupt)
        initializeResources()
    except RuntimeError as ex:
        source = str(ex)
        if "UnsupportedClassVersion" in source:
            import re
            match = re.search(r"([0-9]+)\.[0-9]+", source)
            if match:
                version = int(match.group(1)) - 44
                raise RuntimeError(
                    "%s is older than required Java version %d" %
                    (jvmpath, version)) from ex
        raise
Beispiel #13
0
def startJVM(*args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvmpath.

    The default classpath is determined by ``jpype.getClassPath()``.
    The default jvmpath is determined by ``jpype.getDefaultJVMPath()``.

    Parameters:
     *args (Optional, str[]): Arguments to give to the JVM.
        The first argument may be the path the JVM.

    Keyword Arguments:
      jvmpath (str):  Path to the jvm library file,
        Typically one of (``libjvm.so``, ``jvm.dll``, ...)
        Using None will apply the default jvmpath.
      classpath (str,[str]): Set the classpath for the JVM.
        This will override any classpath supplied in the arguments
        list. A value of None will give no classpath to JVM.
      ignoreUnrecognized (bool): Option to ignore
        invalid JVM arguments. Default is False.
      convertStrings (bool): Option to force Java strings to
        cast to Python strings. This option is to support legacy code
        for which conversion of Python strings was the default. This
        will globally change the behavior of all calls using
        strings, and a value of True is NOT recommended for newly
        developed code.

        The default value for this option during 0.7 series is
        True.  The option will be False starting in 0.8. A
        warning will be issued if this option is not specified
        during the transition period.


    Raises:
      OSError: if the JVM cannot be started or is already running.
      TypeError: if an invalid keyword argument is supplied
        or a keyword argument conflicts with the arguments.

     """
    if _jpype.isStarted():
        raise OSError('JVM is already started')
    global _JVM_started
    if _JVM_started:
        raise OSError('JVM cannot be restarted')

    args = list(args)

    # JVM path
    jvmpath = None
    if args:
        # jvm is the first argument the first argument is a path or None
        if not args[0] or not args[0].startswith('-'):
            jvmpath = args.pop(0)
    if 'jvmpath' in kwargs:
        if jvmpath:
            raise TypeError('jvmpath specified twice')
        jvmpath = kwargs.pop('jvmpath')
    if not jvmpath:
        jvmpath = getDefaultJVMPath()

    # Classpath handling
    if _hasClassPath(args):
        # Old style, specified in the arguments
        if 'classpath' in kwargs:
            # Cannot apply both styles, conflict
            raise TypeError('classpath specified twice')
        classpath = None
    elif 'classpath' in kwargs:
        # New style, as a keywork
        classpath = kwargs.pop('classpath')
    else:
        # Not speficied at all, use the default classpath
        classpath = _classpath.getClassPath()

    # Handle strings and list of strings.
    if classpath:
        if isinstance(classpath, str):
            args.append('-Djava.class.path=%s' % _handleClassPath([classpath]))
        elif hasattr(classpath, '__iter__'):
            args.append('-Djava.class.path=%s' % _handleClassPath(classpath))
        else:
            raise TypeError("Unknown class path element")

    ignoreUnrecognized = kwargs.pop('ignoreUnrecognized', False)
    convertStrings = kwargs.pop('convertStrings', False)

    if kwargs:
        raise TypeError("startJVM() got an unexpected keyword argument '%s'" %
                        (','.join([str(i) for i in kwargs])))

    try:
        _jpype.startup(jvmpath, tuple(args), ignoreUnrecognized,
                       convertStrings)
        _JVM_started = True
    except RuntimeError as ex:
        source = str(ex)
        if "UnsupportedClassVersion" in source:
            import re
            match = re.search(r"([0-9]+)\.[0-9]+", source)
            if match:
                version = int(match.group(1)) - 44
                raise RuntimeError(
                    "%s is older than required Java version %d" %
                    (jvmpath, version)) from ex
        raise

    _jpype._java_lang_Class = None
    _jpype._java_lang_Object = _jpype.JClass("java.lang.Object")
    _jpype._java_lang_Throwable = _jpype.JClass("java.lang.Throwable")
    _jpype._java_lang_Exception = _jpype.JClass("java.lang.Exception")
    _jpype._java_lang_Class = _jpype.JClass("java.lang.Class")
    _jpype._java_lang_String = _jpype.JClass("java.lang.String")

    _jpype._java_lang_RuntimeException = _jpype.JClass(
        "java.lang.RuntimeException")

    # Preload needed classes
    _jpype._java_lang_Boolean = _jpype.JClass("java.lang.Boolean")
    _jpype._java_lang_Byte = _jpype.JClass("java.lang.Byte")
    _jpype._java_lang_Character = _jpype.JClass("java.lang.Character")
    _jpype._java_lang_Short = _jpype.JClass("java.lang.Short")
    _jpype._java_lang_Integer = _jpype.JClass("java.lang.Integer")
    _jpype._java_lang_Long = _jpype.JClass("java.lang.Long")
    _jpype._java_lang_Float = _jpype.JClass("java.lang.Float")
    _jpype._java_lang_Double = _jpype.JClass("java.lang.Double")

    # Bind types
    _jpype.JString.class_ = _jpype._java_lang_String
    _jpype.JObject.class_ = _jpype._java_lang_Object
    _jtypes.JBoolean.class_ = _jpype._java_lang_Boolean.TYPE
    _jtypes.JByte.class_ = _jpype._java_lang_Byte.TYPE
    _jtypes.JChar.class_ = _jpype._java_lang_Character.TYPE
    _jtypes.JShort.class_ = _jpype._java_lang_Short.TYPE
    _jtypes.JInt.class_ = _jpype._java_lang_Integer.TYPE
    _jtypes.JLong.class_ = _jpype._java_lang_Long.TYPE
    _jtypes.JFloat.class_ = _jpype._java_lang_Float.TYPE
    _jtypes.JDouble.class_ = _jpype._java_lang_Double.TYPE
    _jtypes.JBoolean._hints = _jcustomizer.getClassHints("boolean")
    _jtypes.JByte._hints = _jcustomizer.getClassHints("byte")
    _jtypes.JChar._hints = _jcustomizer.getClassHints("char")
    _jtypes.JShort._hints = _jcustomizer.getClassHints("short")
    _jtypes.JInt._hints = _jcustomizer.getClassHints("int")
    _jtypes.JLong._hints = _jcustomizer.getClassHints("long")
    _jtypes.JFloat._hints = _jcustomizer.getClassHints("float")
    _jtypes.JDouble._hints = _jcustomizer.getClassHints("double")

    # Table for automatic conversion to objects "JObject(value, type)"
    _jpype._object_classes = {}
    # These need to be deprecated so that we can support casting Python objects
    _jpype._object_classes[bool] = _jpype._java_lang_Boolean
    _jpype._object_classes[int] = _jpype._java_lang_Long
    _jpype._object_classes[float] = _jpype._java_lang_Double
    _jpype._object_classes[str] = _jpype._java_lang_String
    _jpype._object_classes[type] = _jpype._java_lang_Class
    _jpype._object_classes[object] = _jpype._java_lang_Object
    _jpype._object_classes[_jpype._JClass] = _jpype._java_lang_Class
    _jpype._object_classes[_jtypes.JBoolean] = _jpype._java_lang_Boolean
    _jpype._object_classes[_jtypes.JByte] = _jpype._java_lang_Byte
    _jpype._object_classes[_jtypes.JChar] = _jpype._java_lang_Character
    _jpype._object_classes[_jtypes.JShort] = _jpype._java_lang_Short
    _jpype._object_classes[_jtypes.JInt] = _jpype._java_lang_Integer
    _jpype._object_classes[_jtypes.JLong] = _jpype._java_lang_Long
    _jpype._object_classes[_jtypes.JFloat] = _jpype._java_lang_Float
    _jpype._object_classes[_jtypes.JDouble] = _jpype._java_lang_Double
    _jpype._object_classes[type(None)] = _jpype._java_lang_Object
    _jpype._object_classes[_jpype.JString] = _jpype._java_lang_String

    # Set up table of automatic conversions of Python primitives
    # this table supports "JArray(type)"
    _jpype._type_classes = {}
    _jpype._type_classes[bool] = _jtypes.JBoolean
    _jpype._type_classes[int] = _jtypes.JLong
    _jpype._type_classes[float] = _jtypes.JDouble
    _jpype._type_classes[str] = _jpype._java_lang_String
    _jpype._type_classes[type] = _jpype._java_lang_Class
    _jpype._type_classes[object] = _jpype._java_lang_Object
    _jpype._type_classes[_jpype.JString] = _jpype._java_lang_String
    _jpype._type_classes[_jpype.JObject] = _jpype._java_lang_Object
    _jinit.runJVMInitializers()

    _jpype.JClass('org.jpype.JPypeKeywords').setKeywords(
        list(_pykeywords._KEYWORDS))
Beispiel #14
0
def runNoMethodCode(path):
    _jpype.startup(path, tuple(), False, False)
    cls = _jpype.PyJPClass("java.lang.String")
    methods = cls.getClassMethods()
    methods[0].__code__  # RuntimeError
Beispiel #15
0
def runStartupBadArgs(path):
    _jpype.startup(path)
Beispiel #16
0
def runStartup(path):
    _jpype.startup(path, tuple(), False, False)
Beispiel #17
0
def startJVM(*args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvmpath.

    The default classpath is determined by ``jpype.getClassPath()``.
    The default jvmpath is determined by ``jpype.getDefaultJVMPath()``.

    Parameters:
     *args (Optional, str[]): Arguments to give to the JVM.
        The first argument may be the path the JVM.

    Keyword Arguments:
      jvmpath (str):  Path to the jvm library file,
        Typically one of (``libjvm.so``, ``jvm.dll``, ...)
        Using None will apply the default jvmpath.
      classpath (str,[str]): Set the classpath for the jvm.
        This will override any classpath supplied in the arguments
        list. A value of None will give no classpath to JVM.
      ignoreUnrecognized (bool): Option to JVM to ignore
        invalid JVM arguments. Default is False.
      convertStrings (bool): Option to JPype to force Java strings to
        cast to Python strings. This option is to support legacy code
        for which conversion of Python strings was the default. This
        will globally change the behavior of all calls using
        strings, and a value of True is NOT recommended for newly 
        developed code.

        The default value for this option during 0.7 series is 
        True.  The option will be False starting in 0.8. A
        warning will be issued if this option is not specified
        during the transition period.


    Raises:
      OSError: if the JVM cannot be started or is already running.
      TypeError: if an invalid keyword argument is supplied
        or a keyword argument conflicts with the arguments.

     """
    if _jpype.isStarted():
        raise OSError('JVM is already started')
    global _JVM_started
    if _JVM_started:
        raise OSError('JVM cannot be restarted')
    _JVM_started = True

    args = list(args)

    # JVM path
    jvmpath = None
    if args:
        # jvm is the first argument the first argument is a path or None
        if not args[0] or not args[0].startswith('-'):
            jvmpath = args.pop(0)
    if 'jvmpath' in kwargs:
        if jvmpath:
            raise TypeError('jvmpath specified twice')
        jvmpath = kwargs.pop('jvmpath')
    if not jvmpath:
        jvmpath = getDefaultJVMPath()

    # Classpath handling
    if _hasClassPath(args):
        # Old style, specified in the arguments
        if 'classpath' in kwargs:
            # Cannot apply both styles, conflict
            raise TypeError('classpath specified twice')
        classpath = None
    elif 'classpath' in kwargs:
        # New style, as a keywork
        classpath = kwargs.pop('classpath')
    else:
        # Not speficied at all, use the default classpath
        classpath = _classpath.getClassPath()

    # Handle strings and list of strings.
    if classpath:
        if isinstance(classpath, (str, _jtypes._unicode)):
            args.append('-Djava.class.path=%s' % _handleClassPath([classpath]))
        elif hasattr(classpath, '__iter__'):
            args.append('-Djava.class.path=%s' % _handleClassPath(classpath))
        else:
            raise TypeError("Unknown class path element")

    ignoreUnrecognized = kwargs.pop('ignoreUnrecognized', False)

    if not "convertStrings" in kwargs:
        import warnings
        warnings.warn("""
-------------------------------------------------------------------------------
Deprecated: convertStrings was not specified when starting the JVM. The default
behavior in JPype will be False starting in JPype 0.8. The recommended setting
for new code is convertStrings=False.  The legacy value of True was assumed for
this session. If you are a user of an application that reported this warning,
please file a ticket with the developer.
-------------------------------------------------------------------------------
""")

    convertStrings = kwargs.pop('convertStrings', True)


    if kwargs:
        raise TypeError("startJVM() got an unexpected keyword argument '%s'"
                        % (','.join([str(i) for i in kwargs])))

    _jpype.startup(jvmpath, tuple(args), ignoreUnrecognized, convertStrings)
    _initialize()
Beispiel #18
0
def startJVM(*args, **kwargs):
    """
    Starts a Java Virtual Machine.  Without options it will start
    the JVM with the default classpath and jvmpath.  

    The default classpath is determined by ``jpype.getClassPath()``.
    The default jvmpath is determined by ``jpype.getDefaultJVMPath()``.

    Parameters:
     *args (Optional, str[]): Arguments to give to the JVM.
        The first argument may be the path the JVM.

    Keyword Arguments:
      jvmpath (str):  Path to the jvm library file,
        Typically one of (``libjvm.so``, ``jvm.dll``, ...) 
        Using None will apply the default jvmpath.
      classpath (str,[str]): Set the classpath for the jvm.
        This will override any classpath supplied in the arguments
        list. A value of None will give no classpath to JVM.
      ignoreUnrecognized (bool): Option to JVM to ignore
        invalid JVM arguments. Default is False.

    Raises:
      OSError: if the JVM cannot be started or is already running.
      TypeError: if an invalid keyword argument is supplied 
        or a keyword argument conflicts with the arguments.

     """
    if _jpype.isStarted():
        raise OSError('JVM is already started')
    global _JVM_started
    if _JVM_started:
        raise OSError('JVM cannot be restarted')
    _JVM_started = True

    args = list(args)

    # JVM path
    jvmpath = None
    if args:
        # jvm is the first argument the first argument is a path or None
        if not args[0] or not args[0].startswith('-'):
            jvmpath = args.pop(0)
    if 'jvmpath' in kwargs:
        if jvmpath:
            raise TypeError('jvmpath specified twice')
        jvmpath = kwargs.pop('jvmpath')
    if not jvmpath:
        jvmpath = getDefaultJVMPath()

    # Classpath handling
    if _hasClassPath(args):
        # Old style, specified in the arguments
        if 'classpath' in kwargs:
            # Cannot apply both styles, conflict
            raise TypeError('classpath specified twice')
        classpath = None
    elif 'classpath' in kwargs:
        # New style, as a keywork
        classpath = kwargs.pop('classpath')
    else:
        # Not speficied at all, use the default classpath
        classpath = _classpath.getClassPath()

    # Handle strings and list of strings.
    if classpath:
        if isinstance(classpath, (str, _jtypes._unicode)):
            args.append('-Djava.class.path=%s' % classpath)
        else:
            args.append('-Djava.class.path=%s' %
                        (_classpath._SEP.join(classpath)))

    ignoreUnrecognized = kwargs.pop('ignoreUnrecognized', False)

    if kwargs:
        raise TypeError("startJVM() got an unexpected keyword argument '%s'" %
                        (','.join([str(i) for i in kwargs])))

    _jpype.startup(jvmpath, tuple(args), ignoreUnrecognized)
    _initialize()