Top Description Fields Constructors Methods
org.python.core

public Class PrePy

extends Object
Class Inheritance
Known Direct Subclasses
org.python.core.Py
Imports
java.io.File, .IOException, .InputStream, java.net.JarURLConnection, .MalformedURLException, .URI, .URISyntaxException, .URL, .URLConnection, java.security.AccessControlException, java.util.Properties, java.util.logging.Level, .Logger, java.util.regex.Matcher, .Pattern, jnr.posix.util.Platform

This class is part of the Jython run-time system, and contains only "pre-Python" data and methods that may safely be used before the type system is ready. The Jython type system springs into existence in response to a program's first use of any PyObject, for example when creating the first interpreter. When preparing an application (from the command line options, say) for creation of the first interpreter, it useful to defer type system creation until pre-Python configuration is complete. See PEP 432 for further rationale.

Creation of the type system may happen as a side effect of referring using (almost) any object from a class that statically refers to a PyObject, for example Py or PySystemState. The present class is intended to hold utility methods and configuration useful in the pre-Python phase.

Field Summary

Modifier and TypeField and Description
public static final int
COMMENT

Options#verbose level providing detail during correct functioning.

public static final int
DEBUG

Options#verbose level providing detail in support of debugging or tracing.

public static final int
ERROR

Options#verbose level indicating an error that prevents correct results.

protected static final Logger
private static final Level[]
LEVELS

A mapping from the traditional "verbosity" found in Options#verbose to the JUL Level, offset such that verbosity ERROR maps to element 1 which contains Level.SEVERE.

protected static final Logger
logger

Our name-spaced root logger is "org.python".

public static final int
MESSAGE

Options#verbose level for messages that confirm correct functioning.

private static int
savedVerbosity

Used by maybeWrite(Level, String), the terminus of all verbosity-based logging calls, to detect changes made directly to Options#verbose.

public static final int
WARNING

Options#verbose level indicating an unexpected event, still working correctly.

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
private static String

Returns:

the full name of the jar file containing this class, null if not available.
_getJarFileName
()

Utility-method to obtain the name (including absolute path) of the currently used jython-jar-file.

public static String

Returns:

the first line with content, or ""
getCommandResult
(String...
as strings (as for ProcessBuilder)
command
)

Run a command as a sub-process and return as the result the first line of output that consists of more than white space.

public static String

Returns:

the first line with content, or ""
getCommandResultWindows
(String...
as strings (as for ProcessBuilder)
command
)

A specialised wrapper on getCommandResult(String...) for the Windows platform, where we have to consult the environment variable ComSpec to locate the command processor.

public static String

Returns:

usual Jython bin-dir as absolute path
getDefaultBinDir
()

Infers the usual Jython bin-dir from the position of the jar-file returned by getJarFileName() byr replacing the file name with "bin".

public static String

Returns:

usual Jython-executable as absolute path
getDefaultExecutableName
()

Infers the usual Jython executable name from the position of the jar-file returned by getJarFileName() by replacing the file name with "bin/jython".

private static Level
getEffectiveLoggingLevel(Logger logger)

Convenience function to get the effective level of a given Logger, looking up the parent chain.

public static String

Returns:

the full name of the jar file containing this class, null if not available.
getJarFileName
()

Utility-method to obtain the name (including absolute path) of the currently used jython-jar-file.

public static String

Returns:

the file path or null in the event of a detectable error
getJarFileNameFromURL
(URL
into the JAR
url
)

Return the path in the file system (as a string) of a JAR located using the URL of a class file that it contains.

public static Level
getLoggingLevel()

Convenience function to get the effective level of Logger "org.python".

public static Properties

Returns:

System properties or a new Properties object
getSystemProperties
()

Get the System properties if we are allowed to.

public static String

Returns:

property value or given default
getSystemProperty
(String
of the entry to return
key
,
String
to return if null or disallowed
defaultValue
)

Get a System property if it is defined, not null, and we are allowed to access it, otherwise return the given default.

public static boolean
haveConsole()

Return true iff the console is accessible through System.console().

public static void
increaseLoggingLevel(int
increment on the scale 1=INFO, 2=CONFIG, 3=FINE, ...
n
)

Adjust the level of the Jython logger "org.python" using the traditional "verbosity" system: the bigger the number, the lower the logging threshold.

public static boolean

Returns:

true if (we think) standard input is an interactive stream
isInteractive
()

Determine whether standard input is an interactive stream.

public static boolean

Returns:

true iff thought to be interactive
isInteractive
(InputStream
stream (tested only for System.in)
fp
,
String filename)

Check whether an input stream is interactive.

public static Level

Returns:

a corresponding level where the default MESSAGE produces Level.INFO.
levelFromVerbosity
(int
any integer verbosity, where the runtime default MESSAGE = 1
verbosity
)

Translate from the traditional "verbosity" system to JUL Level.

public static void
maybeWrite(String type, String msg, int verbosity)

Log a message at a specified level (if that level is not below the threshold).

public static Level

Returns:

previous logging level
setLoggingLevel
(Level
to set
newLevel
)

Set the level of the Jython logger "org.python" using the standard java.util.logging scale.

private static void
syncLoggingLevel()

Ensure that the logging system threshold is adjusted to match the legacy Options#verbose in the event that that has changed since we last looked.

private static URL

Returns:

corrected URL
tweakWindowsFileURL
(URL
Possibly malformed URL
url
)

If the argument is a jar:file: or file: URL, compensate for a bug in Java's construction of URLs affecting java.io.File and java.net.URLConnection on Windows.

public static int

Returns:

integer verbosity, where the runtime default INFO = 1
verbosityFromLevel
(Level
java.util.logging.Level to translate.
level
)

Translate from JUL Level to equivalent in the traditional "verbosity" system.

public static void
writeComment(String type, String msg)

Submit a message to logging at the severity level COMMENT.

public static void
writeDebug(String type, String msg)

Submit a message to logging at the severity level DEBUG.

public static void
writeError(String type, String msg)

Submit a message to logging at the severity level ERROR.

public static void
writeMessage(String type, String msg)

Submit a message to logging at the severity level MESSAGE.

public static void
writeWarning(String type, String msg)

Submit a message to logging at the severity level WARNING.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

COMMENTback to summary
public static final int COMMENT

Options#verbose level providing detail during correct functioning.

DEBUGback to summary
public static final int DEBUG

Options#verbose level providing detail in support of debugging or tracing.

ERRORback to summary
public static final int ERROR

Options#verbose level indicating an error that prevents correct results.

importLoggerback to summary
protected static final Logger importLogger
LEVELSback to summary
private static final Level[] LEVELS

A mapping from the traditional "verbosity" found in Options#verbose to the JUL Level, offset such that verbosity ERROR maps to element 1 which contains Level.SEVERE.

loggerback to summary
protected static final Logger logger

Our name-spaced root logger is "org.python".

MESSAGEback to summary
public static final int MESSAGE

Options#verbose level for messages that confirm correct functioning.

savedVerbosityback to summary
private static int savedVerbosity

Used by maybeWrite(Level, String), the terminus of all verbosity-based logging calls, to detect changes made directly to Options#verbose.

WARNINGback to summary
public static final int WARNING

Options#verbose level indicating an unexpected event, still working correctly.

Constructor Detail

PrePyback to summary
public PrePy()

Method Detail

_getJarFileNameback to summary
private static String _getJarFileName()

Utility-method to obtain the name (including absolute path) of the currently used jython-jar-file. Usually this is jython.jar, but can also be jython-dev.jar or jython-standalone.jar or something custom.

Returns:String

the full name of the jar file containing this class, null if not available.

getCommandResultback to summary
public static String getCommandResult(String... command)

Run a command as a sub-process and return as the result the first line of output that consists of more than white space. It returns "" on any kind of error.

Parameters
command:String[]

as strings (as for ProcessBuilder)

Returns:String

the first line with content, or ""

getCommandResultWindowsback to summary
public static String getCommandResultWindows(String... command)

A specialised wrapper on getCommandResult(String...) for the Windows platform, where we have to consult the environment variable ComSpec to locate the command processor.

Parameters
command:String[]

as strings (as for ProcessBuilder)

Returns:String

the first line with content, or ""

getDefaultBinDirback to summary
public static String getDefaultBinDir()

Infers the usual Jython bin-dir from the position of the jar-file returned by getJarFileName() byr replacing the file name with "bin". This is intended as an easy fallback for cases where sys.executable is null due to direct launching via the java executable.

Note that this does not necessarily return the actual bin-directory, but instead infers the place where it is usually expected to be.

Returns:String

usual Jython bin-dir as absolute path

getDefaultExecutableNameback to summary
public static String getDefaultExecutableName()

Infers the usual Jython executable name from the position of the jar-file returned by getJarFileName() by replacing the file name with "bin/jython". This is intended as an easy fallback for cases where sys.executable is None due to direct launching via the java executable.

Note that this does not necessarily return the actual executable, but instead infers the place where it is usually expected to be. Use sys.executable to get the actual executable (may be None.

Returns:String

usual Jython-executable as absolute path

getEffectiveLoggingLevelback to summary
private static Level getEffectiveLoggingLevel(Logger logger)

Convenience function to get the effective level of a given Logger, looking up the parent chain. If the root logger is reached without an explicit level set, assume Level.INFO.

getJarFileNameback to summary
public static String getJarFileName()

Utility-method to obtain the name (including absolute path) of the currently used jython-jar-file. Usually this is jython.jar, but can also be jython-dev.jar or jython-standalone.jar or something custom.

Returns:String

the full name of the jar file containing this class, null if not available.

getJarFileNameFromURLback to summary
public static String getJarFileNameFromURL(URL url)

Return the path in the file system (as a string) of a JAR located using the URL of a class file that it contains. Classes in Java can be asked for the URL of their associated resources (including their own class definition), and so the caller of this method may present such a URL as the basis for locating the JAR from which it came.

Three protocols are supported, Java JAR-file protocol, and two JBoss protocols "vfs" and "vfszip".

The JAR-file protocol URL, which must be a jar:file: reference to a contained element (that is, it has a "!/" part) is able to identify an actual JAR in a file system that may then be opened using jarFile = new JarFile(jarFileName). The path to the JAR is returned. If the JAR is accessed by another mechanism (http: say) this will fail.

The JBoss URL must be a reference to a class in vfs:<JAR>/org/python/core/, or the same thing using the vfszip: protocol, where <JAR> stands for the absolute path to the Jython JAR in VFS. There is no "!/" marker: in JBoss VFS a JAR is treated just like a directory and can no longer be opened as a JAR. The method essentially just swaps a VFS protocol for the Java file: protocol. The path returned will be correct only if this naive swap is valid.

Parameters
url:URL

into the JAR

Returns:String

the file path or null in the event of a detectable error

getLoggingLevelback to summary
public static Level getLoggingLevel()

Convenience function to get the effective level of Logger "org.python".

getSystemPropertiesback to summary
public static Properties getSystemProperties()

Get the System properties if we are allowed to. Configuration values set via -Dprop=value to the java command will be found here. If a security manager prevents access, we will return a new (empty) object instead.

Returns:Properties

System properties or a new Properties object

getSystemPropertyback to summary
public static String getSystemProperty(String key, String defaultValue)

Get a System property if it is defined, not null, and we are allowed to access it, otherwise return the given default.

Parameters
key:String

of the entry to return

defaultValue:String

to return if null or disallowed

Returns:String

property value or given default

haveConsoleback to summary
public static boolean haveConsole()

Return true iff the console is accessible through System.console().

increaseLoggingLevelback to summary
public static void increaseLoggingLevel(int n)

Adjust the level of the Jython logger "org.python" using the traditional "verbosity" system: the bigger the number, the lower the logging threshold. This is primarily for the command-line Jython, where each "-v" increases the verbosity by one, on the java.util.logging scale.

Parameters
n:int

increment on the scale 1=INFO, 2=CONFIG, 3=FINE, ...

isInteractiveback to summary
public static boolean isInteractive()

Determine whether standard input is an interactive stream. If the Java system property python.launcher.tty is defined and equal to true or false, then that provides the result. This property is normally supplied by the launcher. In the absence of this certainty, we use haveConsole().

Returns:boolean

true if (we think) standard input is an interactive stream

isInteractiveback to summary
public static boolean isInteractive(InputStream fp, String filename)

Check whether an input stream is interactive. This emulates CPython Py_FdIsInteractive within the constraints of pure Java. The input stream is considered ``interactive'' if either

  1. it is System.in and isInteractive() is true, or
  2. the -i flag was given (Options#interactive=true), and the filename associated with it is null or "<stdin>" or "???".
Parameters
fp:InputStream

stream (tested only for System.in)

Returns:boolean

true iff thought to be interactive

levelFromVerbosityback to summary
public static Level levelFromVerbosity(int verbosity)

Translate from the traditional "verbosity" system to JUL Level. We allow Jython verbosity values beyond the conventional range, treating values <ERROR as ERROR (that is Level.SEVERE) and values >DEBUG (that is Level.FINE) as FINER, FINEST and ALL.

Parameters
verbosity:int

any integer verbosity, where the runtime default MESSAGE = 1

Returns:Level

a corresponding level where the default MESSAGE produces Level.INFO.

maybeWriteback to summary
public static void maybeWrite(String type, String msg, int verbosity)

Log a message at a specified level (if that level is not below the threshold).

Annotations
@SuppressWarnings:deprecation
setLoggingLevelback to summary
public static Level setLoggingLevel(Level newLevel)

Set the level of the Jython logger "org.python" using the standard java.util.logging scale. For backward compatibility with the traditional "verbosity" system, make a corresponding setting of Options#verbose.

Parameters
newLevel:Level

to set

Returns:Level

previous logging level

Annotations
@SuppressWarnings:deprecation

syncLoggingLevelback to summary
private static void syncLoggingLevel()

Ensure that the logging system threshold is adjusted to match the legacy Options#verbose in the event that that has changed since we last looked.

Annotations
@SuppressWarnings:deprecation
tweakWindowsFileURLback to summary
private static URL tweakWindowsFileURL(URL url) throws MalformedURLException

If the argument is a jar:file: or file: URL, compensate for a bug in Java's construction of URLs affecting java.io.File and java.net.URLConnection on Windows. This is a helper for getJarFileNameFromURL(URL).

This bug bites when a JAR file is at a (Windows) UNC location, and a jar:file: URL is derived from Class.getResource() as it is in _getJarFileName(). When URL is supplied to getJarFileNameFromURL(URL), the bug leads to a URI that falsely treats a server as an "authority". It subsequently causes an IllegalArgumentException with the message "URI has an authority component" when we try to construct a File. See https://bugs.java.com/view_bug.do?bug_id=6360233 ("won't fix").

Parameters
url:URL

Possibly malformed URL

Returns:URL

corrected URL

verbosityFromLevelback to summary
public static int verbosityFromLevel(Level level)

Translate from JUL Level to equivalent in the traditional "verbosity" system. We return Jython verbosity values beyond the conventional range, enough to enumerate the Java standard levels (e.g FINER returns 4 and ALL returns 6 ).

Parameters
level:Level

java.util.logging.Level to translate.

Returns:int

integer verbosity, where the runtime default INFO = 1

writeCommentback to summary
public static void writeComment(String type, String msg)

Submit a message to logging at the severity level COMMENT.

writeDebugback to summary
public static void writeDebug(String type, String msg)

Submit a message to logging at the severity level DEBUG.

writeErrorback to summary
public static void writeError(String type, String msg)

Submit a message to logging at the severity level ERROR.

writeMessageback to summary
public static void writeMessage(String type, String msg)

Submit a message to logging at the severity level MESSAGE.

writeWarningback to summary
public static void writeWarning(String type, String msg)

Submit a message to logging at the severity level WARNING.