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

os

os

Overview

Miscellaneous operating system dependent functionality

      >>> import os

      >>> dir(os)
      ['CLD_CONTINUED', 'CLD_DUMPED', 'CLD_EXITED', 'CLD_TRAPPED', 'EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER'
      , 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_LOCK', 'F_OK', 'F_TEST', 'F_TLOCK', 'F_ULOCK', 'Mutab
      leMapping', 'NGROUPS_MAX', 'O_ACCMODE', 'O_APPEND', 'O_ASYNC', 'O_CLOEXEC', 'O_CREAT', 'O_DIRECT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NO
      ATIME', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_PATH', 'O_RDONLY', 'O_RDWR', 'O_RSYNC', 'O_SYNC', 'O_TMPFILE', 'O_TRUNC', 'O_WRONLY', 'POSIX_FADV_DONTNEED', 'POSIX_
      FADV_NOREUSE', 'POSIX_FADV_NORMAL', 'POSIX_FADV_RANDOM', 'POSIX_FADV_SEQUENTIAL', 'POSIX_FADV_WILLNEED', 'PRIO_PGRP', 'PRIO_PROCESS', 'PRIO_USER', 'P_ALL', 'P_NOWAIT',
       'P_NOWAITO', 'P_PGID', 'P_PID', 'P_WAIT', 'RTLD_DEEPBIND', 'RTLD_GLOBAL', 'RTLD_LAZY', 'RTLD_LOCAL', 'RTLD_NODELETE', 'RTLD_NOLOAD', 'RTLD_NOW', 'R_OK', 'SCHED_BATCH'
      , 'SCHED_FIFO', 'SCHED_IDLE', 'SCHED_OTHER', 'SCHED_RESET_ON_FORK', 'SCHED_RR', 'SEEK_CUR', 'SEEK_DATA', 'SEEK_END', 'SEEK_HOLE', 'SEEK_SET', 'ST_APPEND', 'ST_MANDLOCK
      ', 'ST_NOATIME', 'ST_NODEV', 'ST_NODIRATIME', 'ST_NOEXEC', 'ST_NOSUID', 'ST_RDONLY', 'ST_RELATIME', 'ST_SYNCHRONOUS', 'ST_WRITE', 'TMP_MAX', 'WCONTINUED', 'WCOREDUMP',
       'WEXITED', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WNOWAIT', 'WSTOPPED', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'XA
      TTR_CREATE', 'XATTR_REPLACE', 'XATTR_SIZE_MAX', 'X_OK', '_DummyDirEntry', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__
      name__', '__package__', '__spec__', '_dummy_scandir', '_execvpe', '_exists', '_exit', '_fwalk', '_get_exports_list', '_putenv', '_spawnvef', '_unsetenv', '_wrap_close'
      , 'abort', 'access', 'altsep', 'chdir', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'cpu_count', 'ctermid', 'curdir', 'defpath', 'de
      vice_encoding', 'devnull', 'dup', 'dup2', 'environ', 'environb', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'ext
      sep', 'fchdir', 'fchmod', 'fchown', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fsdecode', 'fsencode', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'fwalk', 
      'get_blocking', 'get_exec_path', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getegid', 'getenv', 'getenvb', 'geteuid', 'getgid', 'getgrouplist', 'get
      groups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getpriority', 'getresgid', 'getresuid', 'getsid', 'getuid', 'getxattr', 'initgroups', 'i
      satty', 'kill', 'killpg', 'lchown', 'linesep', 'link', 'listdir', 'listxattr', 'lockf', 'lseek', 'lstat', 'major', 'makedev', 'makedirs', 'minor', 'mkdir', 'mkfifo', '
      mknod', 'name', 'nice', 'open', 'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pipe', 'pipe2', 'popen', 'posix_fadvise', 'posix_fallocate', 'pr
      ead', 'putenv', 'pwrite', 'read', 'readlink', 'readv', 'remove', 'removedirs', 'removexattr', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sched_get_priority_m
      ax', 'sched_get_priority_min', 'sched_getaffinity', 'sched_getparam', 'sched_getscheduler', 'sched_param', 'sched_rr_get_interval', 'sched_setaffinity', 'sched_setpara
      m', 'sched_setscheduler', 'sched_yield', 'sendfile', 'sep', 'set_blocking', 'set_inheritable', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setp
      riority', 'setregid', 'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'setxattr', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp',
       'spawnvpe', 'st', 'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective
      _ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sync', 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'terminal_size', 'times', '
      times_result', 'truncate', 'ttyname', 'umask', 'uname', 'uname_result', 'unlink', 'unsetenv', 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitid', 'waitid_result', 
      'waitpid', 'walk', 'write', 'writev']
    

shutil

shutil

Overview

High-level file operations

Usage

Live Demo

Reference

sys @python3 docs

Reference

os @python3 docs

These slides are based on

customised version of

Hakimel's reveal.js

framework