Moduly, alebo aj knižnice ak chcete potrebujeme do našich programov importovat. To sa dá vykonat
troma spôsobmy:
Pre výpis všetkých funkcií a premenných, ktoré obsahuje napr. modul sys použijeme nasledovné:
>>>import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__',
'__stdin__', '__stdout__', '_getframe', 'builtin_module_names',
'byteorder', 'copyright', 'displayhook', 'dllhandle', 'exc_info',
'excepthook', 'exec_prefix', 'executable', 'getdefaultencoding',
'getrecursionlimit', 'getrefcount', 'hexversion', 'last_traceback',
'last_type', 'last_value', 'maxint', 'modules', ...]
Medzi najbežnejšie moduly patria sys,math a time
- Modul sys:
Obsah tohto modulu sme si už vypísali. Napr. funkcia exit() spôsobí opustenie prostredia python.
Dalej premenna ps1 obsahuje ">>>", co oznacuje v prostredí pythona, že sa caká na další príkaz.
>>> import sys
>>>sys.ps1=‘awaiting order: ‘
awaiting order:
Modul math:
>>> import math
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil',
'cos', 'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot',
'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
Je zrejmé, že tento modul obsahuje základné matemaické funkcie ako sínus:
sin arcsin:
asin
hyperbolický sínus:
sinh ... Uvedme si príklad:
>>> pow(5,2)
25
>>> 5**2
25
Modul time:
import time
now = time.localtime(time.time())
print time.asctime(now)
print time.strftime("%y/%m/%d %H:%M", now)
print time.strftime("%a %b %d", now)
print time.strftime("%c", now)
print time.strftime("%I %p", now)
print time.strftime("%Y-%m-%d %H:%M:%S %Z", now)
year, month, day, hour, minute, second, weekday, yearday, daylight = now
print "%04d-%02d-%02d" % (year, month, day)
print "%02d:%02d:%02d" % (hour, minute, second)
print ("MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN")[weekday], yearday
Výpis bude vyzerat neako takto:
Sun Dec 02 12:51:00 2007
07/12/02 12:51
Sun Dec 02
12/02/07 12:51:00
12 PM
2007-12-02 12:51:00 Central Europe Standard Time
2007-12-02
12:51:00
SUN 336