Top Inners Fields Constructors Methods
org.python.util

public Class jython

extends Object
Class Inheritance
Imports
java.io.File, .FileInputStream, .FileNotFoundException, .IOException, .InputStream, .PrintStream, java.util.LinkedList, .List, .Properties, java.util.logging.ConsoleHandler, .Level, .Logger, .SimpleFormatter, java.util.zip.ZipEntry, .ZipFile, org.python.Version, org.python.core.BytecodeLoader, .CompileMode, .Options, .PrePy, .Py, .PyCode, .PyException, .PyFile, .PyList, .PyNullImporter, .PyObject, .PyString, .PyStringMap, .PySystemState, .RegistryKey, .imp

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
jython.CommandLineOptions

Class providing a parser for Jython command line options.

private static enum
jython.Status

Exit status: must have OK.ordinal()==0

Field Summary

Modifier and TypeField and Description
public static final String
CONSOLE_LOG_FORMAT

The default format for console log messages in the command-line Jython.

private static ConsoleHandler
consoleHandler

The console handler we normally attach to "org.python".

private static final String
private static final Logger
logger

The root of the Jython Logger hierarchy, named "org.python".

private static final String
pack-priv static final String
usageBody

The message additional to usageHeader output when asked for help.

pack-priv static final String
usageHeader

The message output when reporting command-line errors and when asked for help.

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
private static boolean

Returns:

true iff a value was set
addDefault
(Properties
to be (possibly) updated
registry
,
String
at which to set value
key
,
String
to set (or null for no setting)
value
)

If the key is not currently present and the passed value is not null, sets the key to the value in the given Properties object.

private static void
addDefaultsFromEnvironment(Properties
to be (possibly) updated
registry
)

Provides default registry entries from particular supported environment variables, obtained by calls to getenv(String).

private static void
addFSEncoded(Iterable<String>
of Strings
source
,
PyList
list
destination
)

Append strings to a PyList as bytes/str objects.

private static void
addWarnOptionsFromEnv(PyList
the list to which the options are appended.
opts
)

Append options from the environment variable PYTHONWARNINGS, respecting the -E option.

private static void
configureSimpleFormatter(String
to set for java.util.logging.SimpleFormatter
format
)

Try to set the format for SimpleFormatter if no other mechanism has been provided, and security allows it.

private static void
exit(jython.Status status)

Exit Jython with status (converted to an integer).

private static synchronized ConsoleHandler

Returns:

Configured consoleHandler
getConsoleHandler
()

Get or lazily create the console handler we normally attach to "org.python", which uses SimpleFormatter and accepts all levels of message.

private static String

Returns:

the corresponding value or defaultValue.
getenv
(String
to access in the environment (if allowed by Options#ignore_environment==false).
name
)

The same as getenv with a null default value.

private static String

Returns:

the corresponding value or defaultValue.
getenv
(String
to access in the environment (if allowed by Options#ignore_environment==false).
name
,
String
to return if name is not defined, is "" or access is forbidden.
defaultValue
)

Get the value of an environment variable, respecting Options#ignore_environment (the -E option), or return the given default if the variable is undefined or the security environment prevents access.

public static void
loggingToConsole()

Events from within the Jython implementation are surfaced through the java.util.logging.Logger org.python or a child of it.

public static void
loggingToDefault()

Mostly reverse the effects of loggingToConsole(), by removing from the "org.python" logger the handler that prints to the console, and setting the "org.python" logger to propagate records to its parent handlers.

public static void
main(String[]
arguments to the program.
args
)

Main Jython program, following the structure and logic of CPython main.c to produce the same behaviour.

private static void
optionNotSupported(char option)

Non-fatal error message when ignoring unsupported option (usually one valid for CPython).

private static void
printError(String
suitable to use in String.format(format, args)
format
,
Object...
zero or more args
args
)

Print "jython: <formatted args>" on System.err as one line.

public static void
run(String[] args)
Deprecated

Now equivalent to main(String[]), which is to be preferred.

private static jython.Status

Returns:

Status.OK on normal termination, Status.NO_FILE if the file cannot be read, or Status.ERROR on other IOExceptions.
runFile
(String
the name of the file or null meaning "???"
filename
,
InteractiveConsole
to do the work
interp
)

Attempt to open the named file and execute it in the interpreter as __main__, as in runStream(InputStream, String, InteractiveConsole).

public static int

Returns:

0 on normal termination (otherwise throws PyException).
runJar
(String
The path to the filename to run.
filename
)

Runs a JAR file, by executing the code found in the file __run__.py, which should be in the root of the JAR archive.

private static jython.Status

Returns:

Status.OK or Status.NOT_RUN (if the file was not an archive).
runMainFromImporter
(PyString
to run (FS encoded name)
archive
)

Attempt to treat a file as a source of imports, import a module __main__, and run it.

private static jython.Status

Returns:

Status.OK on normal termination.
runModule
(String
to run
moduleName
,
boolean
replace sys.argv[0] with the file name of the module source runpy._run_module_as_main option.
set_argv0
)

Attempt to run a module as the __main__ module, via a call to runpy._run_module_as_main.

private static jython.Status

Returns:

Status.OK on normal termination.
runSimpleFile
(InputStream
Python source code
fp
,
String
appears FS-encoded in variable __file__ and in error messages
filename
,
PythonInterpreter
to do the work
interp
)

Execute the stream fp as a file, in the given interpreter, as __main__.

private static void
runStartupFile(InteractiveConsole
to do the work
interp
)

Attempt to execute the file named in the registry entry python.startup, which may also have been set via the environment variable JYTHONSTARTUP.

private static jython.Status

Returns:

Status.OK on normal termination.
runStream
(InputStream
Python source code
fp
,
String
the name of the file or null meaning "???"
filename
,
InteractiveConsole
to do the work
interp
)

Execute the stream fp in the given interpreter.

pack-priv static jython.Status

Returns:

the status given as the argument.
usage
(jython.Status
if == 0 full help version on System.out.
status
)

Print a full usage message onto System.out or a brief usage message onto System.err.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

CONSOLE_LOG_FORMATback to summary
public static final String CONSOLE_LOG_FORMAT

The default format for console log messages in the command-line Jython. See java.util.logging.SimpleFormatter for an explanation of the syntax.

This format is used in the absence of other logging preferences, and only if property python.logging.default is not defined. Jython tests for definitions in the system properties of java.util.logging.config.class, java.util.logging.config.file, and java.util.logging.SimpleFormatter.format and if none of these is defined, it sets the last of them to this value.

You can choose something else, for example to log with millisecond time stamps, launch Jython as:

jython -vv -J-Djava.util.logging.SimpleFormatter.format="[%1$tT.%1$tL] %3$s: (%4$s) %5$s%n"
Depending on your shell, the argument may need quoting or escaping.
consoleHandlerback to summary
private static ConsoleHandler consoleHandler

The console handler we normally attach to "org.python". See getConsoleHandler()

loggerback to summary
private static final Logger logger

The root of the Jython Logger hierarchy, named "org.python".

PYTHON_CONSOLE_CLASSback to summary
private static final String PYTHON_CONSOLE_CLASS
usageBodyback to summary
pack-priv static final String usageBody

The message additional to usageHeader output when asked for help.

usageHeaderback to summary
pack-priv static final String usageHeader

The message output when reporting command-line errors and when asked for help.

Constructor Detail

jythonback to summary
public jython()

Method Detail

addDefaultback to summary
private static boolean addDefault(Properties registry, String key, String value)

If the key is not currently present and the passed value is not null, sets the key to the value in the given Properties object. Thus, it provides a default value for a subsequent getProperty().

Parameters
registry:Properties

to be (possibly) updated

key:String

at which to set value

value:String

to set (or null for no setting)

Returns:boolean

true iff a value was set

addDefaultsFromEnvironmentback to summary
private static void addDefaultsFromEnvironment(Properties registry)

Provides default registry entries from particular supported environment variables, obtained by calls to getenv(String). If a corresponding entry already exists in the properties passed, it takes precedence.

Parameters
registry:Properties

to be (possibly) updated

addFSEncodedback to summary
private static void addFSEncoded(Iterable<String> source, PyList destination)

Append strings to a PyList as bytes/str objects. These might come from the command line, or any source with the possibility of non-ascii values.

Parameters
source:Iterable<String>

of Strings

destination:PyList

list

addWarnOptionsFromEnvback to summary
private static void addWarnOptionsFromEnv(PyList opts)

Append options from the environment variable PYTHONWARNINGS, respecting the -E option.

Parameters
opts:PyList

the list to which the options are appended.

configureSimpleFormatterback to summary
private static void configureSimpleFormatter(String format) throws SecurityException

Try to set the format for SimpleFormatter if no other mechanism has been provided, and security allows it. Note that the absolute fall-back format is: "%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%6$s%n", defined ultimately in sun.util.logging.LoggingSupport.

Parameters
format:String

to set for java.util.logging.SimpleFormatter

Exceptions
SecurityException:
if not allowed to read or set necessary properties.
exitback to summary
private static void exit(jython.Status status)

Exit Jython with status (converted to an integer).

getConsoleHandlerback to summary
private static synchronized ConsoleHandler getConsoleHandler() throws SecurityException

Get or lazily create the console handler we normally attach to "org.python", which uses SimpleFormatter and accepts all levels of message. The format will be that currently assigned in the system property java.util.logging.SimpleFormatter.format, which in turn is a succinct format CONSOLE_LOG_FORMAT, if no other configuration mechanism has been provided by the application.

Returns:ConsoleHandler

Configured consoleHandler

Exceptions
SecurityException:
if no permission to adjust logging

getenvback to summary
private static String getenv(String name)

The same as getenv with a null default value.

Parameters
name:String

to access in the environment (if allowed by Options#ignore_environment==false).

Returns:String

the corresponding value or defaultValue.

getenvback to summary
private static String getenv(String name, String defaultValue)

Get the value of an environment variable, respecting Options#ignore_environment (the -E option), or return the given default if the variable is undefined or the security environment prevents access. An empty string value from the environment is treated as undefined.

This accesses the read-only Java copy of the system environment directly, not os.environ so that it is safe to use before Python types are available.

Parameters
name:String

to access in the environment (if allowed by Options#ignore_environment==false).

defaultValue:String

to return if name is not defined, is "" or access is forbidden.

Returns:String

the corresponding value or defaultValue.

loggingToConsoleback to summary
public static void loggingToConsole()

Events from within the Jython implementation are surfaced through the java.util.logging.Logger org.python or a child of it. When Jython is used interactively, we normally want these to emerge on the console, in a succinct form, not via the java.util.logging root logger. This method is called by main(String[]) to achieve that.

The root logger format is hard to read for humans. The logging level of the handler defaults to INFO, and does not respond to the -v option. (It could be made to, but then all logging would be be turned up together.) This method makes these adjustments to logging:

  • The format SimpleFormatter is replaced with a simpler format (but only if no other logging customisation is present). (Affects all logging.)
  • A console handler is installed for logger org.python using that a SimpleFormatter and accepts all levels.
  • Logger org.python is told not to propagate records to parent handlers (so that messages are not emitted twice.
The level of logger org.python and its child loggers by default, which determines admission of logging, reflects the "verbosity" set by the `-v` option.
loggingToDefaultback to summary
public static void loggingToDefault()

Mostly reverse the effects of loggingToConsole(), by removing from the "org.python" logger the handler that prints to the console, and setting the "org.python" logger to propagate records to its parent handlers. The method does not try to reset the property java.util.logging.SimpleFormatter.format, which is in any case only read during static initialisation by SimpleFormatter.

mainback to summary
public static void main(String[] args)

Main Jython program, following the structure and logic of CPython main.c to produce the same behaviour. The argument to the method is the argument list supplied after the class name in the java command. Arguments up to the executable script name are options for Jython; arguments after the executable script are supplied in sys.argv. "Executable script" here means a Python source file name, a module name (following the -m option), a literal command (following the -c option), or a JAR file name (following the -jar option). As a special case of the file name, "-" is allowed, meaning take the script from standard input.

The main difference for the caller stems from a difference between C and Java: in C, the argument list (argv) begins with the program name, while in Java all elements of (args) are arguments to the program.

Parameters
args:String[]

arguments to the program.

optionNotSupportedback to summary
private static void optionNotSupported(char option)

Non-fatal error message when ignoring unsupported option (usually one valid for CPython).

printErrorback to summary
private static void printError(String format, Object... args)

Print "jython: <formatted args>" on System.err as one line.

Parameters
format:String

suitable to use in String.format(format, args)

args:Object[]

zero or more args

runback to summary
public static void run(String[] args)

Deprecated

Now equivalent to main(String[]), which is to be preferred.

Annotations
@Deprecated
runFileback to summary
private static jython.Status runFile(String filename, InteractiveConsole interp)

Attempt to open the named file and execute it in the interpreter as __main__, as in runStream(InputStream, String, InteractiveConsole). This may raise a Python exception, including SystemExit. If the file cannot be opened, or using it throws a Java IOException that is not converted to a PyException (i.e. not within the executing code), it is reported via printError(String, Object...), and reflected in the return status. If the file can be opened, its parent directory will be inserted at sys.argv[0].

Parameters
filename:String

the name of the file or null meaning "???"

interp:InteractiveConsole

to do the work

Returns:jython.Status

Status.OK on normal termination, Status.NO_FILE if the file cannot be read, or Status.ERROR on other IOExceptions.

runJarback to summary
public static int runJar(String filename)

Runs a JAR file, by executing the code found in the file __run__.py, which should be in the root of the JAR archive. Note that __name__ is set to the base name of the JAR file and not to "__main__" (for historical reasons). This method does not handle exceptions. the caller should handle any (Py)Exceptions thrown by the code.

Parameters
filename:String

The path to the filename to run.

Returns:int

0 on normal termination (otherwise throws PyException).

runMainFromImporterback to summary
private static jython.Status runMainFromImporter(PyString archive)

Attempt to treat a file as a source of imports, import a module __main__, and run it. If the file is suitable (e.g. it's a directory or a ZIP archive) the method places the file first on sys.path, so that __main__ and its packaged dependencies may be found in it. This permits a zip file containing Python source to be run when given as a first argument on the command line. It may be that the file is not of a type that can be imported, in which case the return indicates this.

Parameters
archive:PyString

to run (FS encoded name)

Returns:jython.Status

Status.OK or Status.NOT_RUN (if the file was not an archive).

runModuleback to summary
private static jython.Status runModule(String moduleName, boolean set_argv0)

Attempt to run a module as the __main__ module, via a call to runpy._run_module_as_main. Exceptions raised by the imported module, including SystemExit, if not handled by runpy itself, will propagate out of this method. Note that if runpy cannot import the module it calls sys.exit with a message, which will raise SystemExit from this method.

Parameters
moduleName:String

to run

set_argv0:boolean

replace sys.argv[0] with the file name of the module source runpy._run_module_as_main option.

Returns:jython.Status

Status.OK on normal termination.

runSimpleFileback to summary
private static jython.Status runSimpleFile(InputStream fp, String filename, PythonInterpreter interp)

Execute the stream fp as a file, in the given interpreter, as __main__. The file name provided must correspond to the stream. In particular, the file name extension "$py.class" will cause the stream to be interpreted as compiled code. For streams that are not really files, this name may be a conventional one like "<stdin>", however this method will not treat a console stream as interactive.

Parameters
fp:InputStream

Python source code

filename:String

appears FS-encoded in variable __file__ and in error messages

interp:PythonInterpreter

to do the work

Returns:jython.Status

Status.OK on normal termination.

runStartupFileback to summary
private static void runStartupFile(InteractiveConsole interp)

Attempt to execute the file named in the registry entry python.startup, which may also have been set via the environment variable JYTHONSTARTUP. This may raise a Python exception, including SystemExit that propagates to the caller. If the file cannot be opened, or using it throws a Java IOException that is not converted to a PyException (i.e. not within the executing code), it is reported via printError(String, Object...).

Parameters
interp:InteractiveConsole

to do the work

runStreamback to summary
private static jython.Status runStream(InputStream fp, String filename, InteractiveConsole interp)

Execute the stream fp in the given interpreter. If fp refers to a stream associated with an interactive device (console or terminal input), execute Python source statements from the stream in the interpreter as __main__. Otherwise, the file name provided must correspond to the stream, as in runSimpleFile(InputStream, String, PythonInterpreter).

Parameters
fp:InputStream

Python source code

filename:String

the name of the file or null meaning "???"

interp:InteractiveConsole

to do the work

Returns:jython.Status

Status.OK on normal termination.

usageback to summary
pack-priv static jython.Status usage(jython.Status status)

Print a full usage message onto System.out or a brief usage message onto System.err.

Parameters
status:jython.Status

if == 0 full help version on System.out.

Returns:jython.Status

the status given as the argument.

org.python.util back to summary

pack-priv Class jython.CommandLineOptions

extends Object
Class Inheritance

Class providing a parser for Jython command line options. Many of the allowable options set values directly in the static Options as the parser runs, while others set values in (an instance) of this class.

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static enum
jython.CommandLineOptions.Action

Possible actions to take after processing the options.

Field Summary

Modifier and TypeField and Description
pack-priv jython.CommandLineOptions.Action
action

The action to take after processing the options.

pack-priv List<String>
argv

Arguments after the first non-option, therefore arguments to the executable program.

pack-priv String
command

Argument to the -c option.

pack-priv String
filename

First argument that is not an option (therefore the executable file).

pack-priv boolean
help

-h or --help option.

pack-priv boolean
jar

-jar option.

pack-priv static final char
JAR_OPTION

Valid long-name options.

pack-priv String
message

Set informatively when action==ERROR.

pack-priv String
module

Argument to the -m option.

pack-priv static final OptionScanner.LongSpec[]
pack-priv static final String
PROGRAM_OPTS

Valid single character options.

pack-priv Properties
properties

Collects definitions made with the -D option directly to Jython (not java -D).

pack-priv int
verbosity

Count of -v options.

pack-priv boolean
version

-V or --version option.

pack-priv List<String>
warnoptions

Arguments collected from succesive -W options.

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
private void
_parse(String[] args)

Parser implementation.

private void
_parse(OptionScanner scanner, String[] args)

Parse options into object state, until we encounter the first argument.

private void
error(String message, Object... args)

Set the error message as String.format(message, args) and set the action to Action#ERROR.

private void
optionD(OptionScanner scanner)

Helper for option -Dprop=v, adding to the "post-properties".

pack-priv static jython.CommandLineOptions
parse(String[]
from program invocation.
args
)

Parse the arguments into the static Options and a returned instance of this class.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

actionback to summary
pack-priv jython.CommandLineOptions.Action action

The action to take after processing the options.

argvback to summary
pack-priv List<String> argv

Arguments after the first non-option, therefore arguments to the executable program.

commandback to summary
pack-priv String command

Argument to the -c option.

filenameback to summary
pack-priv String filename

First argument that is not an option (therefore the executable file).

helpback to summary
pack-priv boolean help

-h or --help option.

jarback to summary
pack-priv boolean jar

-jar option.

JAR_OPTIONback to summary
pack-priv static final char JAR_OPTION

Valid long-name options.

messageback to summary
pack-priv String message

Set informatively when action==ERROR.

moduleback to summary
pack-priv String module

Argument to the -m option.

PROGRAM_LONG_OPTSback to summary
pack-priv static final OptionScanner.LongSpec[] PROGRAM_LONG_OPTS
PROGRAM_OPTSback to summary
pack-priv static final String PROGRAM_OPTS

Valid single character options. ':' means expect an argument following.

propertiesback to summary
pack-priv Properties properties

Collects definitions made with the -D option directly to Jython (not java -D).

verbosityback to summary
pack-priv int verbosity

Count of -v options.

versionback to summary
pack-priv boolean version

-V or --version option.

warnoptionsback to summary
pack-priv List<String> warnoptions

Arguments collected from succesive -W options.

Constructor Detail

CommandLineOptionsback to summary
pack-priv CommandLineOptions()

Method Detail

_parseback to summary
private void _parse(String[] args)

Parser implementation. Do not call this twice on the same instance.

_parseback to summary
private void _parse(OptionScanner scanner, String[] args)

Parse options into object state, until we encounter the first argument. This is a helper to _parse(String[]).

errorback to summary
private void error(String message, Object... args)

Set the error message as String.format(message, args) and set the action to Action#ERROR.

optionDback to summary
private void optionD(OptionScanner scanner) throws SecurityException

Helper for option -Dprop=v, adding to the "post-properties". (This is a clash-in-waiting with Python.) The effect is slightly different from -J-Dprop=v, which contributes to the "pre-properties".

parseback to summary
pack-priv static jython.CommandLineOptions parse(String[] args)

Parse the arguments into the static Options and a returned instance of this class.

Parameters
args:String[]

from program invocation.

org.python.util back to summary

pack-priv final Enum jython.CommandLineOptions.Action

extends Enum<jython.CommandLineOptions.Action>
Class Inheritance

Possible actions to take after processing the options.

Field Summary

Modifier and TypeField and Description
public static final jython.CommandLineOptions.Action
public static final jython.CommandLineOptions.Action
public static final jython.CommandLineOptions.Action
public static final jython.CommandLineOptions.Action

Constructor Summary

AccessConstructor and Description
private

Field Detail

ERRORback to summary
public static final jython.CommandLineOptions.Action ERROR
HELPback to summary
public static final jython.CommandLineOptions.Action HELP
RUNback to summary
public static final jython.CommandLineOptions.Action RUN
VERSIONback to summary
public static final jython.CommandLineOptions.Action VERSION

Constructor Detail

Actionback to summary
private Action()

Method Detail

valueOfback to summary
public static jython.CommandLineOptions.Action valueOf(String name)
valuesback to summary
public static jython.CommandLineOptions.Action[] values()
org.python.util back to summary

private final Enum jython.Status

extends Enum<jython.Status>
Class Inheritance

Exit status: must have OK.ordinal()==0

Field Summary

Modifier and TypeField and Description
public static final jython.Status
public static final jython.Status
public static final jython.Status
public static final jython.Status

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static jython.Status
public static jython.Status[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

ERRORback to summary
public static final jython.Status ERROR
NO_FILEback to summary
public static final jython.Status NO_FILE
NOT_RUNback to summary
public static final jython.Status NOT_RUN
OKback to summary
public static final jython.Status OK

Constructor Detail

Statusback to summary
private Status()

Method Detail

valueOfback to summary
public static jython.Status valueOf(String name)
valuesback to summary
public static jython.Status[] values()