How To Use Python Sys Module Examples

Python sys module is a standard built-in module which contains variables and methods related to Python interpreter. This article will introduce the sys module contained variables and methods to you with examples about how to use them. Before use them, you should first import sys module with command import sys.

1. Python Sys Module Variables.

  1. sys.argv : Get a list of command-line arguments. The first element is the python program itself. Starting from the second element is the real argument. First we create a python script file test_sys_argv.py, input below code in it.
    import sys
    
    # define a function to print out each element in sys.argv.
    def print_sys_argv():
        
        sys_arg_len = len(sys.argv)
        
        for i in range(sys_arg_len):
            
            print('Argument ',i,'\'s value is ', sys.argv[i])
    
    
    if __name__ == '__main__':
       
       print_sys_argv()
    
    

    Run below command to invoke above python script file.

    >python test_sys_argv.py 1 2 3 4 5 6 hello
    Argument  0 's value is  test_sys_argv.py
    Argument  1 's value is  1
    Argument  2 's value is  2
    Argument  3 's value is  3
    Argument  4 's value is  4
    Argument  5 's value is  5
    Argument  6 's value is  6
    Argument  7 's value is  hello
  2. sys.version : Gets the version information of the Python interpreter.
    >>> import sys
    >>>
    >>> sys.version
    '3.8.5 (default, Aug  5 2020, 09:44:06) [MSC v.1916 64 bit (AMD64)]'
  3. sys.maxsize : The maximum int value.
    >>> import sys
    >>>
    >>> sys.maxsize
    9223372036854775807
  4. sys.path : Return the search path of the python module, it’s default value is PYTHONPATH environment variable’s value. The first element of sys.path is usually an empty string representing the current directory. sys.path is essentially a list which can do append, insert, pop, remove, and other list-related operations. But we always append it to add module lookup path which you want.
    >>> import sys
    >>> sys.path
    ['', 'C:\\Users\\zhaosong\\anaconda3\\envs\\python_example\\python38.zip', 'C:\\Users\\zhaosong\\anaconda3\\envs\\python_example\\DLLs', 'C:\\Users\\zhaosong\\anaconda3\\envs\\python_example\\lib', 'C:\\Users\\zhaosong\\anaconda3\\envs\\python_example', 'C:\\Users\\zhaosong\\anaconda3\\envs\\python_example\\lib\\site-packages']
  5. sys.platform : Returns the name of the operating system platform.
    >>> import sys
    >>>
    >>> sys.platform
    'win32'
  6. sys.stdin : Standard input, used for all interactive input (including the input() function).
    >>> import sys
    
    # read one line from stdin.
    >>> data = sys.stdin.readline()
    hello python sys module
    
    # print out the data line.
    >>> data
    'hello python sys module\n'
  7. sys.stdin and input() : When we use input(‘Please input something! ‘) to get user input, in fact it will output the prompt first and then captures the user input. Below two code example are equivalent.
    # use input() method to prompt user and get input.
    >>> import sys
    >>>
    >>> data = input("please input text : ")
    please input text : hello world
    
    >>> data
    'hello world'
    
    ########################################################
    
    # use sys.stdin.readline() to get user input.
    >>> import sys
    >>>
    >>> print("please input text :")
    please input text :
    
    >>> data = sys.stdin.readline()
    hello world
    
    >>> data
    'hello world\n'
  8. sys.stdout : Standard output, the place where print() function print out.
    >>> import sys
    >>>
    >>> data = 'hello world'
    >>>
    >>> sys.stdout.write(data+'\n')
    hello world
    12 # this is how many charactor has been writen.
    >>>
    >>> print(data)
    hello world
    >>>
    
  9. sys.stdout and print() : When we run code print(obj), we actually call sys.stdout.write(obj+’\n’), it will print the content to the console (the monitor by default), and append a newline character.
  10. sys.stderr : Standard error.
  11. Above three attributes are the standard input, output and error stream of the operating system. They all return a file type object. They support operations such as read(), write(), and flush(), just like the file object opened by the open() method.
  12. sys.modules : sys.modules hold records of modules that have been imported into the current python environment. This is a global dictionary that is loaded into memory when python starts. Every time a new module is imported, sys.modules will automatically record the module in the global dictionary, and on the second attempt to import the module again, python will first look in the dictionary to see if it has ever been imported, if the answer is yes then the import action is ignored, otherwise import it to the global dictionary, thus speeding up the speed of the program. At the same time, it has the basic method of a dictionary. For example, sys.modules.keys() looks at all the keys ( module name ) of the dictionary, sys.modules.values() looks at all the values ( module name and source file ) of the dictionary, and sys.modules[‘sys’] looks at the corresponding values of the ‘sys’ keys.
    >>> import sys
    >>>
    >>> sys.modules
    {'sys': <module 'sys' (built-in)>, 'builtins': <module 'builtins' (built-in)>, '_frozen_importlib': <module: ......' (built-in)>}
    >>>
    >>> sys.modules.keys()
    dict_keys(['sys', 'builtins', ...... 'site', 'atexit'])
    >>> sys.modules.values()
    dict_values([<module 'sys' (built-in)>, <module 'builtins' (built-in)>,...... <module 'atexit' (built-in)>])
    >>>
    >>> sys.modules['sys']
    <module 'sys' (built-in)>
    >>>
    
  13. sys.builtin_module_names : sys.builtin_module_names is a string tuple that contains the names of all modules that have been compiled in the Python interpreter.
    >>> import sys
    >>>
    >>> sys.builtin_module_names
    ('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_contextvars', '_csv', '_datetime', '_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode', '_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_sre', '_stat', '_statistics', '_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', '_xxsubinterpreters', 'array', 'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'parser', 'sys', 'time', 'winreg', 'xxsubtype', 'zlib')
  14. sys.copyright : Copyright information of current Python.
    >>> import sys
    >>>
    >>> sys.copyright
    'Copyright (c) 2001-2020 Python Softwar......All Rights Reserved.'
  15. sys.implementation : The implementation of the currently running python interpreter, such as CPython.
    >>> import sys
    >>>
    >>> sys.implementation
    namespace(cache_tag='cpython-38', hexversion=50857456, name='cpython', version=sys.version_info(major=3, minor=8, micro=5, releaselevel='final', serial=0))
  16. sys.thread_info : Current thread information.
    >>> import sys
    >>>
    >>> sys.thread_info
    sys.thread_info(name='nt', lock=None, version=None)

2. Python Sys Module Methods.

  1. sys.exit(n) : Exit python program, exit(0) means normal exit. If the parameter n is not 0, a SystemExit exception is thrown, which can be caught in the program.
    >>> import sys
    >>> 
    >>> sys.exit(0)
  2. sys.getdefaultencoding() : Gets the operating system current encoding value, the default value is ‘utf-8’.
    >>> import sys
    >>>
    >>> sys.getdefaultencoding()
    'utf-8'
  3. sys.getfilesystemencoding() : Get the file system used encoding, the default value is ‘utf-8’.
    >>> import sys
    >>> 
    >>> sys.getfilesystemencoding()
    'utf-8'
    
  4. sys.getrefcount(object) : Return the number of references to an object. Python has an automatic garbage collection mechanism, which let us not bother with memory management. So how does python know that an object can be garbage collected? Python use a ‘reference count’ to track the number of references per object. The count is incremented by one for every reference to the object, and subtracted by one for every deletion of a reference to the object. When the reference count is zero, it means that no variables point to the object, so the object can be reclaimed to free up the memory it occupies.
  5. The sys.getrefcount(Object) method returns the number of times an object has been referenced. Note that this count start at 1 by default, because when you use the sys.getrefcount(Object) method, it will reference the object once.
    >>> import sys
    >>> 
    >>> str = 'hello python'
    >>> sys.getrefcount(str)
    2
    >>> str_1 = str
    >>> sys.getrefcount(str)
    3
    >>> str_2 = str
    >>> sys.getrefcount(str)
    4
    >>> str_3 = str_1
    >>> sys.getrefcount(str)
    5
    >>> del str_1
    >>> sys.getrefcount(str)
    4
    >>> del str_2
    >>> sys.getrefcount(str)
    3
    >>> sys.getrefcount(1)
    142
    >>> sys.getrefcount(True)
    144
    >>> sys.getrefcount('hello')
    3
    >>> sys.getrefcount(None)
    4837
    

    Note that the examples 1, True, ‘hello’ and None have been referenced many times in the python internal environment, and None has even been referenced 4837 times.

  6. sys.getswitchinterval() : Returns the thread switch time interval. The default value is 0.005 seconds.
    >>> import sys
    >>> 
    >>> sys.getswitchinterval()
    0.005
  7. sys.setswitchinterval(interval) : Set thread switch time interval in seconds.
    >>> import sys
    >>> 
    >>> sys.getswitchinterval()
    0.005
    >>> 
    >>> sys.setswitchinterval(1)
    >>> sys.getswitchinterval()
    1.0
    

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.