Search notes:

Python standard library: sys

import sys

print("\npaths in sys.path:")
for dir in sys.path:
    print("  " + dir)


print("\nPrint without newlines:")
sys.stdout.write('  ')
for i in range(10):
    sys.stdout.write (str(i) + " ")

print("\n\nsys.prefix = " + sys.prefix)
print("  Compare with distutils.sysocnifg.get_python_lib() and site.getsitepackages()")

print("\ngetdefaultencoding: " + sys.getdefaultencoding())

sys.exit(0)
Github repository about-python, path: /standard-library/sys/script.py

dir(sys)

__breakpointhook__
__displayhook__
__doc__
__excepthook__
__interactivehook__
__loader__
__name__
__package__
__spec__
__stderr__
__stdin__
__stdout__
__unraisablehook__
_base_executable Compare with executable
_clear_type_cache
_current_exceptions
_current_frames
_debugmallocstats
_enablelegacywindowsfsencoding
_emsscripten_info information about the environment on an wasm32-emscripten platform. (Python 3.11 - Emsscripten)
_framework
_getframe Compare with _current_frames()
_getquickenedcount
_git
_home
_stdlib_dir
_xoptions A dictionary corresponding to the -X command line option.
addaudithook
api_version The interpreter's C api version. Compare with version.
argv The list of command line arguments with which the Python interpreter was started, argv[0] being the name of the script being executed (except the script was named with -c). Compare with orig_argv
audit
base_exec_prefix
base_prefix
breakpointhook
builtin_module_names The tuple containing the names of the modules that are compiled into the Python interpreter. Compare with sys.modules.keys() (which lists the imported modules) and sys.stdlib_module_names
byteorder endianness (value is either big or small)
call_tracing
copyright
displayhook
dllhandle
dont_write_bytecode If True, importing modules won't write .pyc files. See also the -B command line option and the PYTHONDONTWRITEBYTECODE environment variable
exc_info
excepthook
exec_prefix Root directory of platform dependent files, compare with prefix.
executable The absoulute path of the Python interpreter executable, for example /usr/bin/python or C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\python.exe. Compare with _base_executable
exit Raise a SystemExit exception. Compare with quit() and os._exit().
flags A named tuple that exposes the values of the used command line options
float_info A named tuple holding information about the float type (max, max_exp, max_10_exp, min, min_exp, min_10_exp, dig, mant_dig, epsilon, radix, rounds). Compare with the system's float.h file. See also int_info
float_repr_style A string controlling the behaviour of repr() for floats. Possible values are short (which is the default) and legacy.
get_asyncgen_hooks
get_coroutine_origin_tracking_depth
getallocatedblocks
getdefaultencoding
getfilesystemencodeerrors
getfilesystemencoding
getprofile
getrecursionlimit
getrefcount Returns an object's reference counter.
getsizeof
getswitchinterval
gettrace
getwindowsversion
hash_info
hexversion
implementation Some information about the currently running Python interpreter. See also PEP 421
int_info Information about the internal representation of Python's integers (named tuple with the attributes bits_per_digit, sizeof_digit, default_max_str_digits, str_digits_check_threshold, default_max_str_digits and str_digits_check_threshold, last two added in Python 3.11). See also float_info
intern
is_finalizing
maxsize
maxunicode
meta_path
modules A dictionary that maps module names to loaded modules.
orig_argv See also argv
path A list of directories (strings) where the interpreter tries to locate modules. The value consists of a default (set at compilation time?) and additional directories which can be configured using the PYTHONPATH environment variable. See also the -P command line option and the PYTHONSAFEPATH environment variable.
path_hooks
path_importer_cache
platform Identification of the platform where the interpreter is running. For example win32, linux, emscripten, linux, aix etc. See also os.name and os.uname
platlibdir Usuallly lib (lib64 on Fedora and SuSE)
prefix The base directory of the installation, used to find the standard library and other important files. The value of prefix might be /usr or /usr/lib !. This value is changed in a virtual environment. Compare with base_prefix, exec_prefix and lib
ps1
ps2
pycache_prefix If not None, read/write .pyc files from the specified directory (rather than from __pycache__) See also the command line option -X pycache_prefix and the PYTHONPYCACHEPREFIX environment variable.
set_asyncgen_hooks
set_coroutine_origin_tracking_depth
setprofile
setrecursionlimit
setswitchinterval Sets the thread switch interval in seconds (floating point value).
settrace
stdin, stdout, stderr
stdlib_module_names See also builtin_module_names
thread_info
unraisablehook
version Version number of Python interpreter and additional information. Instead of parsing this string, use sys.version_info and functions of platform module. Compare with api_version.
version_info A tuple storing the interpreter's major, minor, micro, releaselevel and serial values.
warnoptions
winver Available on Windows only: Used to locate registry keys.
This table was produced with
import sys
for e in dir(sys): print(e)

version_info

#!/usr/bin/python

import sys

print(sys.version_info.major)
print(sys.version_info.minor)
print(sys.version_info.micro)
print(sys.version_info.releaselevel)
print(sys.version_info.serial)
Github repository about-python, path: /standard-library/sys/version_info.py

path

sys.path contains a list of directories that are searched for modules/packages when they are tried to be imported.
The directories in this list include:
The entries in sys.path may be modified after Python has initialized itself:
import sys
sys.path.append('path/to/directory/with/package')
import XYZ
Because a string is an iterable, trying to add a path with += (i. e. sys.path += 'path/to/dir') does not do what one might expect. Instead, if insisting on using +=, the path should be added like so: sys.path += ['path/to/dir']
If Python is started with the -s command line option, the user site directory is not added to sys.path.
Python allows to create virtual environments which is added to sys.path when activated, see the Python module venv.
If multiple packages with the same name are located in different directories of the sys.path list, the first package shadows the others, i. e. import pkgname imports the package that is found in the first directory of the list.

modules

modules is a cache for all modules that were imported.
#!/usr/bin/python

import sys

#
#   The type of sys.modules is a dictionary:
#
print(type(sys.modules)) # <class 'dict'>

#
#   Print names of imported modules.
#
for module_name in sys.modules:
    print(module_name)

#
# sys.modules maps from strings to 'class modules':
#
print(type(sys.modules['sys'])) # <class 'module'>
Github repository about-python, path: /standard-library/sys/modules.py

executable

sys.executable prints the absolute path of the Python interpreter (executable).

argv

sys.argv is a list of strings that stores the (relative) path of the currently running script in the first element and the command line arguments that are passed to the script in the remaining elements.
import sys

print()
print("Script was called with %d argument(s)" % (len(sys.argv) - 1))
print("The script name is: ", sys.argv[0])


if len(sys.argv) - 1:

   print()
   print("The argument(s) are:")

   for arg in sys.argv[1:]:
       print("  ", arg)

print()
Github repository about-python, path: /standard-library/sys/argv.py
See also

See also

sys.stdin, sys.stdout and sys.stderr
standard library

Index