Debian Codegraph @

jpyutil.py

raw symbols ◀ ▶ SCIP
Source reconstructed at patch state 1 of 3 — not the installed (fully patched) source.
3 Debian patches touch this file
1 """
2 The main usage of this module is to configure jpy with respect to a given Java version and Python version.
3 The module can also be used as tool. For usage, type:
4
5 python jpyutil.py --help
6
7 The function being invoked here is `write_config_files()` which may also be directly used from your Python code.
8 It will create a file 'jpyconfig.py' and/or a 'jpyconfig.properties' in the given output directory which is usually
9 the one in which the jpy module is installed.
10
11 To programmatically configure the Java Virtual machine, the `init_jvm()` function can be used:
12
13 import jpyutil
14 jpyutil.init_jvm(jvm_maxmem='512M', jvm_classpath=['target/test-classes'])
15 # Without the former call, the following jpy import would create a JVM with default settings
16 import jpy
17
18 The `init_jvm()` can also be called with 'config_file' or 'config' arguments instead. If they are omitted,
19 default configuration values will inferred by first trying to import the module 'jpyconfig.py' (which must
20 therefore be detectable by the Python sys.path). Secondly, the environment variable 'JPY_PY_CONFIG' may point to
21 such a Python configuration file.
22
23 """
24
25 import sys
26 import sysconfig
27 import os
28 import os.path
29 #import os.environ
30 import platform
31 import ctypes
32 import ctypes.util
33 import logging
34 import subprocess
35
36
37 __author__ = "Norman Fomferra (Brockmann Consult GmbH) and contributors"
38 __copyright__ = "Copyright 2015-2018 Brockmann Consult GmbH and contributors"
39 __license__ = "Apache 2.0"
40 __version__ = "2.1.0.dev0"
41
42
43 # Setup a dedicated logger for jpyutil.
44 # This way importing jpyutil does not interfere with logging in other modules
45 logger = logging.getLogger('jpyutil')
46 # Get log level from environment variable JPY_LOG_LEVEL. Default to INFO
47 log_level = os.getenv('JPY_LOG_LEVEL', 'INFO')
48 try:
49 logger.setLevel(getattr(logging, log_level))
50 except AttributeError as ex:
51 print('JPY_LOG_LEVEL must be DEBUG, INFO, WARNING, ERROR or CRITICAL')
52 raise ex
53
54 ch = logging.StreamHandler()
55 ch.setLevel(getattr(logging, log_level))
56 formatter = logging.Formatter('%(name)s - %(levelname)s: %(message)s')
57 ch.setFormatter(formatter)
58 logger.addHandler(ch)
59
60 # Uncomment for debugging
61 # logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
62
63 JDK_HOME_VARS = ('JPY_JAVA_HOME', 'JPY_JDK_HOME', 'JAVA_HOME', 'JDK_HOME',)
64 JRE_HOME_VARS = ('JPY_JAVA_HOME', 'JPY_JDK_HOME', 'JPY_JRE_HOME', 'JAVA_HOME', 'JDK_HOME', 'JRE_HOME', 'JAVA_JRE')
65 JVM_LIB_NAME = 'jvm'
66
67
68 def _get_python_lib_name():
69 try:
70 abiflags = sys.abiflags
71 except AttributeError:
72 abiflags = ''
73 version = sysconfig.get_config_var('VERSION')
74 if not version:
75 version = ''
76 return 'python' + version + abiflags
77
78
79 PYTHON_64BIT = sys.maxsize > 2 ** 32
80 PYTHON_LIB_NAME = _get_python_lib_name()
81
82 PYTHON_LIB_DIR_CONFIG_VAR_NAMES = ('LDLIBRARYDIR', 'srcdir',
83 'BINDIR', 'DESTLIB', 'DESTSHARED',
84 'BINLIBDEST', 'LIBDEST', 'LIBDIR',)
85
86
87 def _get_unique_config_values(names):
88 values = []
89 for name in names:
90 value = sysconfig.get_config_var(name)
91 if value and value not in values:
92 values.append(value)
93 return values
94
95
96 def _add_paths_if_exists(path_list, *paths):
97 for path in paths:
98 if os.path.exists(path) and path not in path_list:
99 path_list.append(path)
100 return path_list
101
102 def _find_loadable_spec_origin(name):
103 import importlib.util
104 spec = importlib.util.find_spec(name)
105 return spec.origin if spec and spec.has_location else None
106
107 def _get_module_path(name, fail=False, install_path=None):
108 """ Find the path to the jpy jni modules. """
109 spec_origin = _find_loadable_spec_origin(name)
110 if not spec_origin:
111 if fail:
112 raise ImportError("module '{}' not found, or is not loadable".format(name))
113 return None
114 return spec_origin if not install_path else os.path.join(install_path, os.path.split(spec_origin)[1])
115
116 def _find_file(search_dirs, *filenames):
117 for filename in filenames:
118 for dir_ in search_dirs:
119 path = os.path.normpath(os.path.join(dir_, filename))
120 path_exists = os.path.exists(path)
121 logger.debug("Exists '%s'? %s" % (path, "yes" if path_exists else "no"))
122 if path_exists:
123 return path
124 return None
125
126
127 def _get_java_api_properties(fail=False, path=None):
128 jpy_config = Properties()
129 jpy_config.set_property('jpy.jpyLib', _get_module_path('jpy', fail=fail, install_path=path))
130 jpy_config.set_property('jpy.jdlLib', _get_module_path('jdl', fail=fail, install_path=path))
131 jpy_config.set_property('jpy.pythonLib', _find_python_dll_file(fail=fail))
132 jpy_config.set_property('jpy.pythonPrefix', sys.prefix)
133 jpy_config.set_property('jpy.pythonExecutable', sys.executable)
134 return jpy_config
135
136
137 def find_jdk_home_dir():
138 """
139 Try to detect the JDK home directory from Maven, if available, or use
140 dedicated environment variables.
141 :return: pathname if found, else None
142 """
143
144 def is_jdk_dir(path):
145 rst = os.path.exists(os.path.join(path, 'include')) and os.path.exists(os.path.join(path, 'lib'))
146 logger.debug(f'Checking {path} for JDK...: {"yes" if rst else "no"}')
147 return rst
148
149 def walk_to_jdk(path):
150 if is_jdk_dir(path):
151 return path
152
153 for root, dir_names, file_names in os.walk(path):
154 for d in dir_names:
155 p = os.path.join(root, d)
156
157 if p and is_jdk_dir(p):
158 return p
159
160 return None
161
162 for name in JDK_HOME_VARS:
163 jdk_home_dir = os.environ.get(name, None)
164 if jdk_home_dir:
165 logger.debug(f'JAVA_HOME set by environment variable to {jdk_home_dir}')
166
167 if is_jdk_dir(jdk_home_dir):
168 return jdk_home_dir
169
170 jdk_dir = walk_to_jdk(jdk_home_dir)
171
172 if jdk_dir:
173 logger.error(f'JAVA_HOME set by environment variable to {jdk_home_dir} but no no "include" or "lib" directory found. Possibly you meant {jdk_dir}?')
174 else:
175 logger.error(f'JAVA_HOME set by environment variable to {jdk_home_dir} but no no "include" or "lib" directory found. Does not appear to be a JDK directory.')
176
177 exit(1)
178
179 logger.debug('Checking Maven for JAVA_HOME...')
180 try:
181 output = subprocess.check_output(['mvn', '-v'])
182 if isinstance(output, bytes) and not isinstance(output, str):
183 # In Python 3, byte arrays must be explicitly converted into strings.
184 output = output.decode('utf-8')
185 for part in output.split('\n'):
186 if part.startswith('Java home:'):
187 path = part.split(':')[1].strip()
188 if path.endswith('jre'):
189 java_home = path[0:-3]
190 logger.debug(f'JAVA_HOME set by maven to {java_home}')
191 return java_home
192
193 except Exception:
194 # maven probably isn't installed or not on PATH
195 logger.debug('Maven not found on PATH. No JAVA_HOME found.')
196
197 return None
198
199 def _java_process_java_home():
200 logger.debug('Checking Java for JAVA_HOME...')
201 try:
202 from java_utilities import lookup_property
203 return lookup_property('java.home', use_env=False)
204 except ImportError:
205 logger.debug("java_utilities not found, skipping java process check")
206 except Exception as e:
207 logger.debug(e, exc_info=True)
208 return None
209
210 def find_jvm_dll_file(java_home_dir=None, fail=False):
211 """
212 Try to detect the JVM's shared library file.
213 :param java_home_dir: The Java JRE or JDK installation directory to be used for searching.
214 :param fail: Controls behaviour when library file cannot be found. If False, use a fallback. If True, raise
215 a runtime error.
216 :return: pathname if found, else None
217 """
218
219 logger.debug("Searching for JVM shared library file")
220
221 if java_home_dir:
222 jvm_dll_path = _find_jvm_dll_file(java_home_dir)
223 if jvm_dll_path:
224 return jvm_dll_path
225
226 jvm_dll_path = os.environ.get('JPY_JVM_DLL', None)
227 if jvm_dll_path:
228 return jvm_dll_path
229
230 for name in JRE_HOME_VARS:
231 java_home_dir = os.environ.get(name, None)
232 if java_home_dir:
233 jvm_dll_path = _find_jvm_dll_file(java_home_dir)
234 if jvm_dll_path:
235 return jvm_dll_path
236
237 java_home_dir = _java_process_java_home()
238 if java_home_dir:
239 jvm_dll_path = _find_jvm_dll_file(java_home_dir)
240 if jvm_dll_path:
241 return jvm_dll_path
242
243 jvm_dll_path = ctypes.util.find_library(JVM_LIB_NAME)
244 if jvm_dll_path:
245 logger.debug("No JVM shared library file found in all search paths. Using fallback %s" % repr(jvm_dll_path))
246 elif fail:
247 raise RuntimeError("can't find any JVM shared library")
248
249 return jvm_dll_path
250
251
252 def _get_jvm_lib_dirs(java_home_dir):
253 machine = platform.machine()
254 arch_dir_name = 'aarch64' if machine == 'aarch64' else 'amd64' if PYTHON_64BIT else 'i386'
255 return (os.path.join(java_home_dir, 'bin'),
256 os.path.join(java_home_dir, 'bin', 'server'),
257 os.path.join(java_home_dir, 'bin', 'client'),
258 os.path.join(java_home_dir, 'bin', 'zero'),
259 os.path.join(java_home_dir, 'bin', arch_dir_name),
260 os.path.join(java_home_dir, 'bin', arch_dir_name, 'server'),
261 os.path.join(java_home_dir, 'bin', arch_dir_name, 'client'),
262 os.path.join(java_home_dir, 'bin', arch_dir_name, 'zero'),
263 os.path.join(java_home_dir, 'lib'),
264 os.path.join(java_home_dir, 'lib', 'server'),
265 os.path.join(java_home_dir, 'lib', 'client'),
266 os.path.join(java_home_dir, 'lib', 'zero'),
267 os.path.join(java_home_dir, 'lib', arch_dir_name),
268 os.path.join(java_home_dir, 'lib', arch_dir_name, 'server'),
269 os.path.join(java_home_dir, 'lib', arch_dir_name, 'client'),
270 os.path.join(java_home_dir, 'lib', arch_dir_name, 'zero'),
271 )
272
273
274 def _get_existing_subdirs(dirs, subdirname):
275 new_dirs = []
276 for dir_ in dirs:
277 new_dir = os.path.join(dir_, subdirname)
278 if os.path.isdir(new_dir):
279 new_dirs.append(new_dir)
280 return new_dirs
281
282 def get_arch():
283 """ Get arch name on Debian """
284 from subprocess import check_output
285 # arch = 'amd64' if PYTHON_64BIT else 'i386'
286 arch = check_output(['dpkg-architecture','-q', 'DEB_BUILD_ARCH_CPU']).strip()
287 if type(arch) != str: # python3
288 arch = arch.decode('utf-8')
289 other_names = { 'ppc64el': 'ppc64le', 'arm64' : 'aarch64',
290 'powerpc' : 'ppc', 'sparc64' : 'sparcv9' }
291 if arch in other_names:
292 arch = other_names[arch]
293 return arch
294
295 def _find_jvm_dll_file(java_home_dir):
296 logger.debug("Searching for JVM shared library file in %s" % repr(java_home_dir))
297
298 if not os.path.exists(java_home_dir):
299 return None
300
301 search_dirs = []
302 jre_home_dir = os.path.join(java_home_dir, 'jre')
303 if os.path.exists(jre_home_dir):
304 search_dirs += _get_jvm_lib_dirs(jre_home_dir)
305 search_dirs += _get_jvm_lib_dirs(java_home_dir)
306
307 arch = get_arch()
308 search_dirs += "/usr/lib/jvm/default-java/lib/server"
309
310 search_dirs = _add_paths_if_exists([], *search_dirs)
311
312 if platform.system() == 'Windows':
313 return _find_file(search_dirs, 'jvm.dll')
314 elif platform.system() == 'Darwin':
315 return _find_file(search_dirs, 'libjvm.dylib')
316
317 # 'Window' and 'Darwin' did not succeed, try 'libjvm.so' on remaining platforms
318 return _find_file(search_dirs, 'libjvm.so')
319
320
321 def _find_python_dll_file(fail=False):
322 logger.debug("Searching for Python shared library file")
323
324 # Prepare list of search directories
325 search_dirs = [sys.prefix]
326
327 # installed_base/lib needs to be added to the search path for Python 3.13t files
328 installed_base = sysconfig.get_config_var('installed_base')
329 if installed_base:
330 search_dirs.append(os.path.join(installed_base, "lib"))
331
332 extra_search_dirs = [sysconfig.get_config_var(name) for name in PYTHON_LIB_DIR_CONFIG_VAR_NAMES]
333 for extra_dir in extra_search_dirs:
334 if extra_dir and extra_dir not in search_dirs and os.path.exists(extra_dir):
335 search_dirs.append(extra_dir)
336
337 if platform.system() == 'Windows':
338 extra_search_dirs = _get_existing_subdirs(search_dirs, "DLLs")
339 search_dirs = extra_search_dirs + search_dirs
340
341 multi_arch_sub_dir = sysconfig.get_config_var('multiarchsubdir')
342 if multi_arch_sub_dir:
343 while multi_arch_sub_dir.startswith('/'):
344 multi_arch_sub_dir = multi_arch_sub_dir[1:]
345 extra_search_dirs = _get_existing_subdirs(search_dirs, multi_arch_sub_dir)
346 search_dirs = extra_search_dirs + search_dirs
347
348 logger.debug("Potential Python shared library search dirs: %s" % repr(search_dirs))
349
350 # Prepare list of possible library file names
351 # Prefer "Install .so name" as first candidate for file_names
352 instsoname = sysconfig.get_config_var("INSTSONAME")
353 file_names = [ instsoname ] if instsoname else []
354
355 # account for Python debug builds
356
357 debug_build = sysconfig.get_config_var('Py_DEBUG')
358
359 # account for Python 3.13+ with GIL disabled
360 dll_suffix = ''
361 if sys.version_info >= (3, 13):
362 if not sys._is_gil_enabled():
363 dll_suffix = 't'
364 dll_suffix += 'd' if debug_build else ''
365
366 vmaj = str(sys.version_info.major)
367 vmin = str(sys.version_info.minor)
368
369 if platform.system() == 'Windows':
370 versions = (vmaj + vmin, vmaj, vmaj + vmin + dll_suffix, '')
371 file_names += ['python' + v + '.dll' for v in versions]
372 elif platform.system() == 'Darwin':
373 versions = (vmaj + "." + vmin, vmaj, vmaj + "." + vmin + dll_suffix, '')
374 file_names += ['libpython' + v + '.dylib' for v in versions]
375 file_names += ['libpython' + v + '.so' for v in versions]
376 else:
377 versions = (vmaj + "." + vmin, vmaj, vmaj + "." + vmin + dll_suffix, '')
378 file_names += ['libpython' + v + '.so' for v in versions]
379
380 logger.debug("Potential Python shared library file names: %s" % repr(file_names))
381
382 python_dll_path = _find_file(search_dirs, *file_names)
383 if python_dll_path:
384 return python_dll_path
385
386 python_dll_path = ctypes.util.find_library(PYTHON_LIB_NAME)
387 if python_dll_path:
388 logger.debug(
389 "No Python shared library file found in all search paths. Using fallback %s" % repr(python_dll_path))
390 elif fail:
391 raise RuntimeError("can't find any Python shared library")
392
393 return python_dll_path
394
395
396 def _read_config(config_file):
397 config = Config()
398 config.load(config_file)
399 return config
400
401
402 def _get_python_api_config(config_file=None):
403 if config_file:
404 # 1. Try argument, if any
405 return _read_config(config_file)
406
407 try:
408 # 2. Try Python import machinery
409 import jpyconfig
410 return jpyconfig
411
412 except ImportError:
413 # 3. Try 'JPY_PY_CONFIG' environment variable, if any
414 config_file = os.environ.get('JPY_PY_CONFIG', None)
415 if config_file:
416 return _read_config(config_file)
417
418 return None
419
420
421 def preload_jvm_dll(jvm_dll_file=None,
422 java_home_dir=None,
423 config_file=None,
424 config=None,
425 fail=True):
426 # if jvm_dll_file is unknown, try getting it from config
427 if not jvm_dll_file:
428 if not config:
429 config = _get_python_api_config(config_file=config_file)
430
431 if config:
432 jvm_dll_file = getattr(config, 'jvm_dll', None)
433 if not java_home_dir:
434 java_home_dir = getattr(config, 'java_home', None)
435
436 # if jvm_dll_file is still unknown, try searching it using java_home_dir
437 if not jvm_dll_file:
438 jvm_dll_file = find_jvm_dll_file(java_home_dir=java_home_dir, fail=fail)
439
440 if jvm_dll_file:
441 logger.debug('Preloading JVM shared library %s' % repr(jvm_dll_file))
442 return ctypes.CDLL(jvm_dll_file, mode=ctypes.RTLD_GLOBAL)
443 else:
444 logger.warning('Failed to preload JVM shared library. No shared library found.')
445 return None
446
447
448 def get_jvm_options(jvm_maxmem=None,
449 jvm_classpath=None,
450 jvm_properties=None,
451 jvm_options=None,
452 config=None):
453 if config:
454 if not jvm_maxmem:
455 jvm_maxmem = getattr(config, 'jvm_maxmem', None)
456 if not jvm_classpath:
457 jvm_classpath = getattr(config, 'jvm_classpath', None)
458 if not jvm_properties:
459 jvm_properties = getattr(config, 'jvm_properties', None)
460 if not jvm_options:
461 jvm_options = getattr(config, 'jvm_options', None)
462
463 jvm_cp = None
464 if jvm_classpath and len(jvm_classpath) > 0:
465 jvm_cp = os.pathsep.join(jvm_classpath)
466 if not jvm_cp:
467 jvm_cp = os.environ.get('JPY_JVM_CLASSPATH', None)
468
469 if not jvm_maxmem:
470 jvm_maxmem = os.environ.get('JPY_JVM_MAXMEM', None)
471
472 java_api_properties = _get_java_api_properties().values
473 if jvm_properties:
474 # Overwrite jpy_config
475 jvm_properties = dict(list(java_api_properties.items()) + list(jvm_properties.items()))
476 else:
477 jvm_properties = java_api_properties
478
479 options = []
480 if jvm_maxmem:
481 options.append('-Xmx' + jvm_maxmem)
482 if jvm_cp:
483 options.append('-Djava.class.path=' + jvm_cp)
484 if jvm_properties:
485 for key in jvm_properties:
486 value = jvm_properties[key]
487 options.append('-D' + key + '=' + value)
488 if jvm_options:
489 options += jvm_options
490
491 return options
492
493
494 def init_jvm(java_home=None,
495 jvm_dll=None,
496 jvm_maxmem=None,
497 jvm_classpath=None,
498 jvm_properties=None,
499 jvm_options=None,
500 config_file=None,
501 config=None):
502 """
503 Creates a configured Java virtual machine which will be used by jpy.
504
505 :param java_home: The Java JRE or JDK home directory used to search JVM shared library, if 'jvm_dll' is omitted.
506 :param jvm_dll: The JVM shared library file. My be inferred from 'java_home'.
507 :param jvm_maxmem: The JVM maximum heap space, e.g. '400M', '8G'. Refer to the java executable '-Xmx' option.
508 :param jvm_classpath: The JVM search paths for Java class files. Separated by colons (Unix) or semicolons
509 (Windows). Refer to the java executable '-cp' option.
510 :param jvm_properties: A dictionary of key -> value pairs passed to the JVM as Java system properties.
511 Refer to the java executable '-D' option.
512 :param jvm_options: A list of extra options for the JVM. Refer to the java executable options.
513 :param config_file: Extra configuration file (e.g. 'jpyconfig.py') to be loaded if 'config' parameter is omitted.
514 :param config: An optional default configuration object providing default attributes
515 for the 'jvm_maxmem', 'jvm_classpath', 'jvm_properties', 'jvm_options' parameters.
516 :return: a tuple (cdll, actual_jvm_options) on success, None otherwise.
517 """
518 if not config:
519 config = _get_python_api_config(config_file=config_file)
520
521 cdll = preload_jvm_dll(jvm_dll_file=jvm_dll,
522 java_home_dir=java_home,
523 config_file=config_file,
524 config=config,
525 fail=False)
526
527 import jpy
528
529 if not jpy.has_jvm():
530 jvm_options = get_jvm_options(jvm_maxmem=jvm_maxmem,
531 jvm_classpath=jvm_classpath,
532 jvm_properties=jvm_properties,
533 jvm_options=jvm_options,
534 config=config)
535 logger.debug('Creating JVM with options %s' % repr(jvm_options))
536 jpy.create_jvm(options=jvm_options)
537 try:
538 py_lib_initializer = jpy.get_type('org.jpy.PyLibInitializer')
539 py_lib_initializer.initPyLib(
540 _find_python_dll_file(fail=True),
541 _get_module_path('jpy', fail=True),
542 _get_module_path('jdl', fail=True)
543 )
544 except ValueError:
545 # It's valid to not have jpy.jar on the classpath if you don't expect java to call into python
546 logger.debug("Unable to find org.jpy.PyLibInitializer on classpath")
547 pass
548 else:
549 jvm_options = None
550
551 # print('jvm_dll =', jvm_dll)
552 # print('jvm_options =', jvm_options)
553 return cdll, jvm_options
554
555
556 class Config:
557 def load(self, path):
558 """
559 Read Python file from 'path', execute it and return object that stores all variables of the
560 Python code as attributes.
561 :param path:
562 :return:
563 """
564 with open(path) as f:
565 code = f.read()
566 exec(code, {}, self.__dict__)
567
568
569 class Properties:
570 def __init__(self, values=None):
571 if values:
572 self.keys = list(values.keys())
573 self.values = values.copy()
574 else:
575 self.keys = []
576 self.values = {}
577
578 def set_property(self, key, value):
579 if value:
580 if key not in self.keys:
581 self.keys.append(key)
582 self.values[key] = value
583 else:
584 if key in self.keys:
585 self.keys.remove(key)
586 self.values.pop(key)
587
588 def get_property(self, key, default_value=None):
589 return self.values[key] if key in self.values else default_value
590
591 def store(self, path, comments=()):
592 with open(path, 'w') as f:
593 for comment in comments:
594 f.write('# ' + str(comment).replace('\\', '\\\\') + '\n')
595 for key in self.keys:
596 value = self.get_property(key)
597 if value:
598 f.write(str(key) + ' = ' + str(value).replace('\\', '\\\\') + '\n')
599 else:
600 f.write(str(key) + ' =\n')
601
602 def load(self, path):
603 self.__init__()
604 with open(path) as f:
605 lines = f.readlines()
606 for line in lines:
607 if line and len(line) > 0 and not line.startswith('#'):
608 tokens = line.split('=')
609 if len(tokens) == 2:
610 self.set_property(tokens[0].strip(), tokens[1].strip().replace('\\\\', '\\'))
611 else:
612 raise ValueError('illegal Java properties format ' + line)
613
614
615 def _execute_python_scripts(scripts, **kwargs):
616 import subprocess
617
618 failures = 0
619 for script in scripts:
620 exit_code = subprocess.call([sys.executable, script], **kwargs)
621 if exit_code:
622 failures += 1
623 return failures
624
625
626 def write_config_files(out_dir='.',
627 java_home_dir=None,
628 jvm_dll_file=None,
629 install_dir=None,
630 req_java_api_conf=True,
631 req_py_api_conf=True,
632 jvm_properties=None,
633 jvm_options=None):
634 """
635 Writes the jpy configuration files for Java and/or Python.
636
637 :param out_dir: output directory, must exist
638 :param java_home_dir: optional home directory of the Java JRE or JDK installation
639 :param jvm_dll_file: optional file to JVM shared library file
640 :param install_dir: optional path to where to searfh for modules
641 :param req_java_api_conf: whether to write the jpy configuration file 'jpyconfig.properties' for Java
642 :param req_py_api_conf: whether to write the jpy configuration file 'jpyconfig.py' for Python
643 :return: zero on success, otherwise an error code
644 """
645 import datetime
646
647 retcode = 0
648
649 tool_name = os.path.basename(__file__)
650
651 py_api_config_basename = 'jpyconfig.py'
652 java_api_config_basename = 'jpyconfig.properties'
653
654 if not jvm_dll_file:
655 jvm_dll_file = find_jvm_dll_file(java_home_dir=java_home_dir)
656 if jvm_dll_file:
657 py_api_config_file = os.path.join(out_dir, py_api_config_basename)
658 try:
659 with open(py_api_config_file, 'w') as f:
660 f.write("# Created by '%s' tool\n" % tool_name)
661 f.write(
662 "# This file is read by the 'jpyutil' module in order to load and configure the JVM from Python\n")
663 if java_home_dir:
664 f.write('java_home = %s\n' % repr(java_home_dir))
665 f.write('jvm_dll = %s\n' % repr(jvm_dll_file))
666 f.write('jvm_maxmem = None\n')
667 f.write('jvm_classpath = []\n')
668 if jvm_properties is None:
669 f.write('jvm_properties = {}\n')
670 else:
671 f.write('jvm_properties = ' + str(jvm_properties) + '\n')
672 if jvm_options is None:
673 f.write('jvm_options = []\n')
674 else:
675 f.write('jvm_options = [\'' + jvm_options + '\']\n')
676 logger.info("jpy Python API configuration written to '%s'" % py_api_config_file)
677 except Exception:
678 logger.exception("Error while writing Python API configuration")
679 if req_py_api_conf:
680 retcode = 1
681 else:
682 logger.error("Can't determine any JVM shared library")
683 if req_py_api_conf:
684 retcode = 2
685
686 try:
687 java_api_config_file = os.path.join(out_dir, java_api_config_basename)
688 java_api_properties = _get_java_api_properties(fail=req_java_api_conf, path=install_dir)
689 java_api_properties.store(java_api_config_file, comments=[
690 "Created by '%s' tool" % tool_name,
691 "This file is read by the jpy Java API (org.jpy.PyLib class) in order to find shared libraries"])
692 logger.info("jpy Java API configuration written to '%s'" % java_api_config_file)
693 except Exception:
694 logger.exception("Error while writing Java API configuration")
695 if req_java_api_conf:
696 retcode = 3
697
698 return retcode
699
700
701 def _main():
702 import argparse
703
704 out_default = os.path.dirname(os.path.abspath(__file__))
705
706 parser = argparse.ArgumentParser(description='Generate configuration files for the jpy Python API (jpyconfig.py)\n'
707 'and the jpy Java API (jpyconfig.properties).')
708 parser.add_argument("-o", "--out", action='store', default=out_default,
709 help="Output directory for the generated configuration files. Defaults to " + out_default)
710 parser.add_argument("--java_home", action='store', default=None, help="Java JDK or JRE home directory. Can also be "
711 "set using one of the environment variables "
712 + " | ".join(JRE_HOME_VARS) + ".")
713 parser.add_argument("--jvm_dll", action='store', default=None, help="Java JVM shared library file. Usually inferred"
714 " from java_home option. Can also be set "
715 "using environment variable JPY_JVM_DLL.")
716 parser.add_argument("--log_file", action='store', default=None, help="Optional log file.")
717 parser.add_argument("--log_level", action='store', default='INFO',
718 help="Possible values: DEBUG, INFO, WARNING, ERROR. Default is INFO.")
719 parser.add_argument("-j", "--req_java", action='store_true', default=False,
720 help="Require that Java API configuration succeeds.")
721 parser.add_argument("-p", "--req_py", action='store_true', default=False,
722 help="Require that Python API configuration succeeds.")
723 parser.add_argument("--install_dir", action='store', default=None, help="Optional. Used during pip install of JPY")
724 args = parser.parse_args()
725
726 # Using _ suffix to avoid shadowing global log_level variable
727 log_level_ = getattr(logging, args.log_level.upper(), None)
728 if not isinstance(log_level_, int):
729 raise ValueError('Invalid log level: %s' % log_level_)
730
731 log_format = '%(levelname)s: %(message)s'
732 log_file = args.log_file
733 if log_file:
734 logging.basicConfig(format=log_format, level=log_level_, filename=log_file, filemode='w')
735 else:
736 logging.basicConfig(format=log_format, level=log_level_)
737
738 try:
739 retcode = write_config_files(out_dir=args.out,
740 java_home_dir=args.java_home,
741 jvm_dll_file=args.jvm_dll,
742 req_java_api_conf=args.req_java,
743 req_py_api_conf=args.req_py,
744 install_dir=args.install_dir)
745 except:
746 logger.exception("Configuration failed")
747 retcode = 100
748
749 if retcode == 0:
750 logger.info("Configuration completed successfully")
751
752 exit(retcode)
753
754
755 if __name__ == '__main__':
756 _main()