User Tools

Site Tools


program_lang:python_base

Python bases

Modules and predefined functions

List molules

# /usr/bin/python3
Python 3.6.10 (default, Jan 16 2020, 09:12:04) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> help("modules")

Import a python library

>>> import math
>>> result = math.log2(5) # return the base-2 logarithm
>>> print(result) # Output: 2.321928094887362
2.321928094887362
>>> result = math.sqrt(5)
>>> print(result) # Output: 2.321928094887362
2.23606797749979
>>> result = math.sqrt(4)
>>> print(result) # Output: 2.321928094887362
2.0

Import only one function from a library:

>>> from math import pi
>>> print("The value of pi is", pi)

List all available Modules

print( help('modules'))

Reading Module Documentation

To read the doc of a module, in terminal, type pydoc module_name, or in Python program call help(module_name).

# python 3

import os

# print the module's online manual
print(help(os))

Note: the documentation from pydoc is not identical to the official documentation. Doc from pydoc is generated from the module source code, and is terse and technical.
List Module's Function/Variable Names

    dir(module_name) → list all names exported by the module module_name.
    dir() → list all names in current scope (but not standard functions). To list standard functions, import __builtin__ first, then dir(__builtin__).

# python 3

import re

# print all names exported by the module
print(dir(re))

# output

# ['A', 'ASCII', 'DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'Match', 'Pattern', 'RegexFlag', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__', '_cache', '_compile', '_compile_repl', '_expand', '_locale', '_pickle', '_special_chars_map', '_subx', 'compile', 'copyreg', 'enum', 'error', 'escape', 'findall', 'finditer', 'fullmatch', 'functools', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'template']

Using Module

import module_name → load a module.

module_name.function_name → call a function in module.

# python 3

# import the standard module named os

import os

# example of using a function
# get current dir
print(os.getcwd())

# /Users/xah/web/xahlee_info/python

Import Function Names from Module

Module's function name can be imported directly by the syntax:

    from module_name import name_1, name_2, … → import several functions.
    from module_name import * → import all functions.

# python 3

from os import getcwd

# current dir
print(getcwd())

Default “module”

All global (variable/function) names in Python are considered to be in the pseudo-module namespace named __main__.

# python 3

print(dir())
# ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

print(dir("__main__"))
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Module Search Paths

Python module search paths is stored in the variable sys.path.

# python 3

import sys
import pprint

# pretty print module search paths
pprint.pprint(sys.path)

# ['/Users/xah/web/xahlee_info/python',
#  '/Users/xah/anaconda3/lib/python37.zip',
#  '/Users/xah/anaconda3/lib/python3.7',
#  '/Users/xah/anaconda3/lib/python3.7/lib-dynload',
#  '/Users/xah/anaconda3/lib/python3.7/site-packages',
#  '/Users/xah/anaconda3/lib/python3.7/site-packages/aeosa']

List Loaded Modules

Loaded module names is stored in the variable sys.modules.

# python 3

import sys
import pprint

# pretty print loaded modules
pprint.pprint(sys.modules)

# sample output
# {'__main__': <module '__main__' from '/Users/xah/web/xahlee_info/python/xxtemp.20190318.38b.py3'>,
#  '_abc': <module '_abc' (built-in)>,
#  '_bootlocale': <module '_bootlocale' from '/Users/xah/anaconda3/lib/python3.7/_bootlocale.py'>,
#  '_codecs': <module '_codecs' (built-in)>,
# ...
#  'zipimport': <module 'zipimport' (built-in)>}

Course 1 : socket

[storage@lnx0001 scripts]$ python
Python 2.7.5 (default, Sep 26 2019, 13:23:47)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> socket.gethostname()
'lnx0001.mydom.lu'
>>> socket.gethostbyname(socket.gethostname())
'10.16.10.64'
>>> socket.gethostbyaddr('127.0.0.1')
('localhost', ['localhost.localdomain', 'localhost4', 'localhost4.localdomain4'], ['127.0.0.1'])
>>> socket.gethostbyname('')
'0.0.0.0'
>>> exit()

Course 2 : custom socket

To communicate between client and server

[storage@lnx0001 scripts]$ vi server_socket.py
import socket
s = socket.socket(socket.AF_INET,socket,SOCK_STREAM)

s.bind((socket.gethostname(),4222)) #bind to IP and port
s.listen(10)      # 10 connexctions max

print ('Server is up. Listening for connections')

client,address = s.accept()
print('Connection to', address, 'established\n')
print('Client object:', client, '\n')
client.send(bytes('Welcome',"utf-8")

s.close()

On client

[storage@lnx0001 scripts]$ vi client_socket.py
import socket
s = socket.socket(socket.AF_INET,socket,SOCK_STREAM)

s.bind((socket.gethostname(),4222)) #bind to IP and port

msg = s.recv(1024)  # 

print ('Msg from server', msg.decode('utf-8'))

s.close()

The same code can be written with a tab and remove the close function which is done automaticaly

[storage@lnx0001 scripts]$ vi server_socket.py
import socket
with socket.socket(socket.AF_INET,socket,SOCK_STREAM) as s:
    
    s.bind((socket.gethostname(),4222)) #bind to IP and port
    s.listen(10)      # 10 connexctions max

    print ('Server is up. Listening for connections')

    client,address = s.accept()
    print('Connection to', address, 'established\n')
    print('Client object:', client, '\n')
    client.send(bytes('Welcome',"utf-8")

Add timeout:

s.settimeout(10) # in seconds
[storage@lnx0001 scripts]$ vi server_socket.py
import socket
with socket.socket(socket.AF_INET,socket,SOCK_STREAM) as s:
    
    s.bind((socket.gethostname(),4222)) #bind to IP and port
    s.settimeout(10) # in seconds
    
    try:
        s.listen(10)      # 10 connexctions max

        print ('Server is up. Listening for connections')

        client,address = s.accept()
        print('Connection to', address, 'established\n')
        print('Client object:', client, '\n')
        client.send(bytes('Welcome',"utf-8")
    exept socket.timeout:
        print('Timeout exceeded, close connection')
program_lang/python_base.txt · Last modified: 2021/01/01 21:25 (external edit)