PBE logo

Sys Module - System-specific parameters and functionsΒΆ

argv - The list of command line arguments passed to a Python script. argv[0] is the script name.

# run myscript.py -a somearg
sys.argv[0]   # "myscript.py"
sys.argv[1]   # "-a"
sys.argv[2]   # "somearg"

byteorder - An indicator of the native byte order.

sys.byteorder   # "little"

builtin_module_names A tuple of strings giving the names of all modules that are compiled into this Python interpreter.

copyright - A string containing the copyright pertaining to the Python interpreter.

print sys.copyright

# Copyright (c) 2001-2006 Python Software Foundation.
# All Rights Reserved.
# [...]

dllhandle - Integer specifying the handle of the Python DLL. Availability: Windows.

sys.dllhandle   # 503316480

displayhook( value) - If value is not None, this function prints it to sys.stdout, and saves it in __builtin__._. (Used in interactive Python session.)

displayhook("abc")   # "abc"
print _              # "abc"

excepthook( type, value, traceback) - This function prints out a given traceback and exception to sys.stderr.

__displayhook__, __excepthook__ - These objects contain the original values of displayhook and excepthook at the start of the program. They are saved so that displayhook and excepthook can be restored in case they happen to get replaced with broken objects.

exc_info( ) - This function returns a tuple of three values that give information about the exception that is currently being handled - type, value, traceback.

try: 1/0
except: exctype, value, t_ob = sys.exc_info()
print exctype     # exceptions.ZeroDivisionError
print value       # integer division or modulo by zero
print t_ob        #
print dir(t_ob)   # ['tb_frame', 'tb_lasti', 'tb_lineno', 'tb_next']
print t_ob.lineno # 1   [line number of exception]

exc_clear( ) - This function clears all information relating to the current or last exception that occurred in the current thread. After calling this function, exc_info() will return three None values until another exception is raised in the current thread or the execution stack returns to a frame where another exception is being handled.

exec_prefix - A string giving the site-specific directory prefix where the platform-dependent Python files are installed; by default, this is also ‘/usr/local’.

sys.exec_prefix   # 'C:\\Python24'

executable - A string giving the name of the executable binary for the Python interpreter, on systems where this makes sense.

sys.executable   # 'C:\\Python24\\pythonw.exe'

exit( [arg]) - Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level. The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered ‘’successful termination’’ and any nonzero value is considered ‘’abnormal termination’’ by shells and the like.

sys.exit(0)   # exit program successfully
sys.exit(1)   # exit program with an error

exitfunc - Deprecated since release 2.4. Use atexit instead.

getcheckinterval( ) - Return the interpreter’s ‘’check interval’‘; see setcheckinterval().

getcheckinterval()   # 100

getdefaultencoding( ) - Return the name of the current default string encoding used by the Unicode implementation.

getdefaultencoding()   # 'ascii'

getdlopenflags( ) - Return the current value of the flags that are used for dlopen() calls. The flag constants are defined in the dl and DLFCN modules. Availability: Unix.

getfilesystemencoding( ) - Return the name of the encoding used to convert Unicode filenames into system file names, or None if the system default encoding is used. The result value depends on the operating system: On Windows 9x, the encoding is ‘’mbcs’‘. On Mac OS X, the encoding is ‘’utf-8’‘. On Unix, the encoding is the user’s preference according to the result of nl_langinfo(CODESET), or None if the nl_langinfo(CODESET) failed. On Windows NT+, file names are Unicode natively, so no conversion is performed. getfilesystemencoding still returns ‘’mbcs’‘, as this is the encoding that applications should use when they explicitly want to convert Unicode strings to byte strings that are equivalent when used as file names.

getfilesystemencoding()   # 'mbcs'

getrefcount( object) - Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

a = 'abc'
getrefcount(a)   # 2
b = a
getrefcount(b)   # 3

getrecursionlimit( ) - Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by setrecursionlimit().

getrecursionlimit()   # 1000

_getframe( [depth]) - Return a frame object from the call stack. This function should be used for internal and specialized purposes only.

getwindowsversion( ) - Return a tuple containing five components, describing the Windows version currently running. The elements are major, minor, build, platform, and text. text contains a string while all other values are integers. platform may be one of the following values: Constant Platform 0 (VER_PLATFORM_WIN32s) Win32s on Windows 3.1 1 (VER_PLATFORM_WIN32_WINDOWS) Windows 95/98/ME 2 (VER_PLATFORM_WIN32_NT) Windows NT/2000/XP 3 (VER_PLATFORM_WIN32_CE) Windows CE

# in win XP SP2:
getwindowsversion()   # (5, 1, 2600, 2, 'Service Pack 2')

hexversion - The version number encoded as a single integer. This is guaranteed to increase with each version, including proper support for non-production releases. For example, to test that the Python interpreter is at least version 1.5.2, use:

if sys.hexversion >= 0x010502F0:
      # use some advanced feature
    ...
else:
      # use an alternative implementation or warn the user
    ...

last_type , last_value, last_traceback - These three variables are not always defined; they are set when an exception is not handled and the interpreter prints an error message and a stack traceback. Their intended use is to allow an interactive user to import a debugger module and engage in post-mortem debugging without having to re- execute the command that caused the error. (Typical use is “import pdb; pdb.pm()” to enter the post-mortem debugger; see chapter 9, ‘’The Python Debugger,’’ for more information.)

maxint - The largest positive integer supported by Python’s regular integer type. This is at least 2**31-1. The largest negative integer is -maxint-1 – the asymmetry results from the use of 2’s complement binary arithmetic.

maxint   # 2147483647

maxunicode - An integer giving the largest supported code point for a Unicode character. The value of this depends on the configuration option that specifies whether Unicode characters are stored as UCS-2 or UCS-4.

maxunicode   # 65535

modules - This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks.

modules   # [...], 'time': , [...]

path - A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

path   # ['C:\\Python24\\Lib\\idlelib',
# 'C:\\Python24\\lib\\site-packages\\setuptools-0.6c8-py2.4.egg', ...]

platform - This string contains a platform identifier, e.g. ‘sunos5’ or ‘linux1’. This can be used to append platform-specific components to path, for instance.

platform   # 'win32'

prefix - A string giving the site-specific directory prefix where the platform independent Python files are installed; by default, this is the string ‘/usr/local’.

prefix   # 'C:\\Python24'

ps1 , ps2 - Strings specifying the primary and secondary prompt of the interpreter. These are only defined if the interpreter is in interactive mode. Their initial values in this case are ‘>>> ‘ and ‘... ‘.

ps1   # '>>> '
ps2   # '... '

setcheckinterval( interval) - Set the interpreter’s ‘’check interval’‘. This integer value determines how often the interpreter checks for periodic things such as thread switches and signal handlers. The default is 100, meaning the check is performed every 100 Python virtual instructions. Setting it to a larger value may increase performance for programs using threads. Setting it to a value <= 0 checks every virtual instruction, maximizing responsiveness as well as overhead.

setcheckinterval(200)

setdefaultencoding(name) - Set the current default string encoding used by the Unicode implementation.

setdefaultencoding("ascii")   # set encoding used by Unicode to ascii

setdlopenflags( n) - Set the flags used by the interpreter for dlopen() calls, such as when the interpreter loads extension modules. Among other things, this will enable a lazy resolving of symbols when importing a module, if called as sys.setdlopenflags(0). To share symbols across extension modules, call as sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL). Symbolic names for the flag modules can be either found in the dl module, or in the DLFCN module. If DLFCN is not available, it can be generated from /usr/include/dlfcn.h using the h2py script. Availability: Unix.

setprofile( profilefunc) - Set the system’s profile function, which allows you to implement a Python source code profiler in Python.

setrecursionlimit( limit) - Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

setrecursionlimit(2000)     # [default is 1000]

settrace( tracefunc) - Set the system’s trace function, which allows you to implement a Python source code debugger in Python.

settscdump( on_flag) - Activate dumping of VM measurements using the Pentium timestamp counter, if on_flag is true.

settscdump(True)

stdin, stdout, stderr - File objects corresponding to the interpreter’s standard input, output and error streams.

stdout.write("Hello!")     # 'Hello!'
stderr.write("Error!!!")   # 'Error!!!'

tracebacklimit - When this variable is set to an integer value, it determines the maximum number of levels of traceback information printed when an unhandled exception occurs. The default is 1000.

tracebacklimit   # 1000

version - A string containing the version number of the Python interpreter plus additional information on the build number and compiler used.

version
# '2.4.4c1 (#70, Oct 11 2006, 10:59:14) [MSC v.1310 32 bit (Intel)]'

api_version - The C API version for this interpreter. Programmers may find this useful when debugging version conflicts between Python and extension modules.

api_version   # 1012

version_info - A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial.

# in version 2.4.4:
version_info   # (2, 4, 4, 'candidate', 1)

warnoptions - This is an implementation detail of the warnings framework; do not modify this value.

warnoptions   # []

winver - The version number used to form registry keys on Windows platforms.

winver   # 2.4