Notable Standard Library Modules

sys

sys

Overview

sys is a built-in package, which contains Python interpreter's specific parameters and functions

      >>> import sys

      >>> dir(sys)
      ['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '
      _clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'ba
      se_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix
      ', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getdlopen
      flags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementa
      tion', 'int_info', 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path
      _importer_cache', 'platform', 'prefix', 'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrac
      e', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']
    

get current version number of Python

sys.version, sys.version_info


      >>> import sys

      >>> print(sys.version)
      3.5.2 (default, Nov 23 2017, 16:37:01)
      [GCC 5.4.0 20160609]

      >>> print(sys.version_info)
      sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)
    

get current version number of Python - example


      import sys

      if sys.version_info[0] == 2:
        print("Python 2 is running")
      elif sys.version_info[0] == 3:
        print("Python 3 is running")
    

      $ python2.7 sys.version_info.py
      Python 2 is running
    

      $ python3.6 sys.version_info.py
      Python 3 is running
    

get interpreter absolute path

sys.executable


      >>> import sys
      >>> print(sys.executable)
      /usr/bin/python3
    

get module search path

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

      >>> import sys
      >>> for i in sys.path:
      ...     print(i)
      ...
      /home/nemsys/.local/bin
      /usr/lib/python35.zip
      /usr/lib/python3.5
      /usr/lib/python3.5/plat-x86_64-linux-gnu
      /usr/lib/python3.5/lib-dynload
      /home/nemsys/.local/lib/python3.5/site-packages
      /usr/local/lib/python3.5/dist-packages
      /usr/lib/python3/dist-packages
    

get the size of an object in bytes

sys.getsizeof()


      >>> import sys
      >>>
      >>> print(sys.getsizeof(2))
      28
      >>> print(sys.getsizeof(range(1)))
      48
      print(sys.getsizeof(range(1000000)))
      48
      >>> print(sys.getsizeof([1,2,3,4,5]))
      104
      >>> print(sys.getsizeof((1,2,3,4,5)))
      88
      >>> print(sys.getsizeof("a"))
      50
      >>> print(sys.getsizeof("abcabc"))
      55
    

Command line arguments - Overview

Command line arguments/parameters are used to pass information to a program.
Instead of asking the user to feed your program with data interactively (input), you can ask her to pass the data as parameters to the script

      import sys

      # print(sys.argv)

      user_name = sys.argv[1]
      print("Hello {}, how are you today?".format(user_name))
    

      $ python argv_demo.py pesho
    

Command line arguments

sys.argv stores the list of command-line arguments.
Note that the script name is passed implicitly as the first argument!
i.e. sys.argv[0] will store the script name.

Command line arguments - examples


      import sys

      print('Argument List:', sys.argv)
    

      $ python argv_examples.py
      Argument List: ['argv_examples.py']
    

      $ python argv_examples.py arg1
      Argument List: ['argv_examples.py', 'arg1']
    

      $ python argv_examples.py arg1 arg2
      Argument List: ['argv_examples.py', 'arg1', 'arg2']
    

Process variable command line arguments

You can use a for loop over sys.argv list in order to process a variable number of command line arguments

      import sys

      sum = 0

      # get only arguments, without the script name
      args = sys.argv[1:]

      for arg in args:
        sum += int(arg)

      print ("The sum of {} is {}".format(args, sum))
    

      python sum_args.py 1 2 3
      The sum of ['1', '2', '3'] is 6
    

Reference

sys @python3 docs

Notable Standard Library Modules

Notable Standard Library Modules

abc - Abstract Base Classes
asyncio - Asynchronous I/O, event loop, coroutines and tasks
asyncio - Asynchronous I/O, event loop, coroutines and tasks
csv - Write and read tabular data to and from delimited files.
datetime - Basic date and time types.
distutils - Building and installing Python modules
email - Package supporting the parsing, manipulating, and generating email messages.
getopt - Portable parser for command line options; support both short and long option names.
gzip - Interfaces for gzip compression and decompression using file objects.
hashlib - Secure hash and message digest algorithms.
itertools - Functions creating iterators for efficient looping.
json - Encode and decode the JSON format.
logging - Flexible event logging system for applications.
math - Mathematical functions (sin() etc.).
pathlib - Object-oriented filesystem paths
pdb - The Python debugger for interactive interpreters.
pickle - Convert Python objects to streams of bytes and back
pprint - Data pretty printer.
pydoc - Documentation generator and online help system.
random - Generate pseudo-random numbers with various common distributions.
re - Regular expression operations.
shutil - High-level file operations, including copying.
subprocess - Subprocess management.
sqlite3 - A DB-API 2.0 implementation using SQLite 3.x.
sys - Access system-specific parameters and functions.
timeit - Measure the execution time of small code snippets.
tkinter - Interface to Tcl/Tk for graphical user interfaces
unittest - Unit testing framework for Python.
urllib - URL handling modules
urllib.request - for opening and reading URLs
urllib.error - containing the exceptions raised by urllib.request
urllib.parse - for parsing URLs
urllib.robotparser - for parsing robots.txt files
venv - Creation of virtual environments.
xml - Package containing XML processing modules

Reference

Python Module Index

These slides are based on

customised version of

Hakimel's reveal.js

framework