Zanurkuj w Pythonie/Testowanie modułów
Zainstalowane moduły
[edytuj]W konsoli wprowadź: [1]
pydoc modules
przykładowy wynik:
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/variety/__init__.py:105: PyGIWarning: Gtk was imported without specifying a version first. Use gi.require_version('Gtk', '3.0') before import to ensure that the right version gets loaded.
from gi.repository import Gtk, Gdk, GObject # pylint: disable=E0611
/usr/lib/python2.7/dist-packages/variety/VarietyWindow.py:25: PyGIWarning: Notify was imported without specifying a version first. Use gi.require_version('Notify', '0.7') before import to ensure that the right version gets loaded.
from gi.repository import Gtk, Gdk, GdkPixbuf, GObject, Gio, Notify # pylint: disable=E0611
/usr/lib/python2.7/dist-packages/variety/AddPanoramioDialog.py:19: PyGIWarning: WebKit was imported without specifying a version first. Use gi.require_version('WebKit', '3.0') before import to ensure that the right version gets loaded.
from gi.repository import Gtk, WebKit, GObject # pylint: disable=E0611
/usr/lib/python2.7/dist-packages/variety/QuoteWriter.py:19: PyGIWarning: PangoCairo was imported without specifying a version first. Use gi.require_version('PangoCairo', '1.0') before import to ensure that the right version gets loaded.
from gi.repository import Gdk, Pango, PangoCairo, GdkPixbuf, GObject
/usr/lib/python2.7/dist-packages/variety/indicator.py:28: PyGIWarning: AppIndicator3 was imported without specifying a version first. Use gi.require_version('AppIndicator3', '0.1') before import to ensure that the right version gets loaded.
from gi.repository import AppIndicator3 # pylint: disable=E0611
BaseHTTPServer _testcapi gobject re
Bastion _threading_local grp readline
CDROM _version gtk repr
CGIHTTPServer _warnings gtkunixprint resource
Canvas _weakref gzip rexec
ConfigParser _weakrefset hashlib rfc822
Cookie abc heapq rlcompleter
DLFCN aifc hmac robotparser
Dialog alabaster hotshot roman
DocXMLRPCServer antigravity html5lib runpy
FileDialog anydbm htmlentitydefs sched
FixTk argparse htmllib select
HTMLParser array httplib sets
IN ast ihooks sgmllib
Image asynchat image_geometry sha
ImageChops asyncore imaplib shelve
ImageColor atexit imghdr shlex
ImageCrackCode atk imp shutil
ImageDraw audiodev importlib signal
ImageEnhance audioop imputil site
ImageFile babel indicator_keyboard sitecustomize
ImageFileIO base64 inspect six
ImageFilter bdb io smtpd
ImageFont binascii itertools smtplib
ImageGL binhex jinja2 sndhdr
ImageGrab bisect json socket
ImageMath bs4 jumble sphinx
ImageOps bsddb keyword sphinx_rtd_theme
ImagePalette bz2 lib2to3 spwd
ImagePath cPickle libexiv2python sqlite3
ImageQt cProfile linecache sre
ImageSequence cStringIO linuxaudiodev sre_compile
ImageStat cairo locale sre_constants
ImageTk calendar logging sre_parse
ImageWin cgi lsb_release ssl
MimeWriter cgitb lxml stat
PIL chardet macpath statvfs
PSDraw chunk macurl2path std_msgs
PngImagePlugin cmath mailbox string
Queue cmd mailcap stringold
ScrolledText code markupbase stringprep
SimpleDialog codecs markupsafe strop
SimpleHTTPServer codeop marshal struct
SimpleXMLRPCServer collections math subprocess
SocketServer colorsys md5 sunau
StringIO commands mhlib sunaudio
TYPES compileall mimetools symbol
Tix compiler mimetypes symtable
Tkconstants configobj mimify sys
Tkdnd contextlib mmap sysconfig
Tkinter cookielib modulefinder syslog
UserDict copy multifile tabnanny
UserList copy_reg multiprocessing talloc
UserString crypt mutex tarfile
_LWPCookieJar csv netrc telnetlib
_MozillaCookieJar ctypes new tempfile
__builtin__ curl nis termios
__future__ curses nntplib test
_abcoll cv ntpath textwrap
_ast cv2 nturl2path this
_bisect cv_bridge numbers thread
_bsddb datetime numpy threading
_codecs dbhash opcode time
_codecs_cn dbm opencv_apps timeit
_codecs_hk dbus operator tkColorChooser
_codecs_iso2022 debconf optparse tkCommonDialog
_codecs_jp decimal os tkFileDialog
_codecs_kr difflib os2emxpath tkFont
_codecs_tw dircache ossaudiodev tkMessageBox
_collections dis pango tkSimpleDialog
_csv distutils pangocairo toaiff
_ctypes doctest parser token
_ctypes_test docutils pdb tokenize
_curses dsextras pickle trace
_curses_panel dumbdbm pickletools traceback
_dbus_bindings dummy_thread pipes ttk
_dbus_glib_bindings dummy_threading pkg_resources tty
_elementtree email pkgutil turtle
_functools encodings platform types
_hashlib ensurepip plistlib unicodedata
_heapq errno popen2 unittest
_hotshot exceptions poplib urllib
_io fcntl posix urllib2
_json filecmp posixfile urlparse
_locale fileinput posixpath user
_lsprof fnmatch pprint uu
_md5 formatter profile uuid
_multibytecodec fpectl pstats validate
_multiprocessing fpformat pty variety
_osx_support fractions pwd variety_lib
_pyio ftplib py_compile warnings
_random functools pyclbr wave
_sha future_builtins pycurl weakref
_sha256 gc pydoc webbrowser
_sha512 genericpath pydoc_data whichdb
_socket genmsg pyexiv2 wsgiref
_sqlite3 genpy pyexpat xdrlib
_sre getopt pygments xml
_ssl getpass pygtk xmllib
_strptime gettext pygtkcompat xmlrpclib
_struct gi pynotify xxsubtype
_symtable gio pytz zipfile
_sysconfigdata glib quopri zipimport
_sysconfigdata_nd glob random zlib
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".
Testowanie modułów
[edytuj]Moduły Pythona to obiekty, które posiadają kilka przydatnych atrybutów. Możemy ich użyć do łatwego testowania własnych modułów. Oto przykład zastosowania triku if __name__:
if __name__ == "__main__":
Zwróćmy uwagę na dwie ważne sprawy: pierwsza, że instrukcja warunkowa if nie wymaga nawiasów, a druga, że if kończy się dwukropkiem, a w następnych liniach wstawiamy wcięty kod.
Podobnie jak w języku C, Python używa == dla porównania i = dla przypisania. W przeciwieństwie do C, w Pythonie nie możemy dokonywać przypisania w dowolnych miejscach kodu, w tym w instrukcji warunkowej (np. if x = 10 nie jest poprawny). Nie ma szansy, aby przypadkowo przypisać wartość do zmiennej, zamiast zastosować porównanie.
|
Na czym polega zastosowany trik? Moduły to obiekty, a każdy z nich posiada wbudowany atrybut __name__, który zależy od tego, w jaki sposób korzystamy z danego modułu. Jeżeli importujemy moduł, wtedy __name__ jest nazwą pliku modułu bez ścieżki do katalogu, czy rozszerzenia pliku. Możemy także uruchomić bezpośrednio moduł jako samodzielny program, a wtedy __name__ przyjmie domyślną wartość "__main__".
>>> import odbchelper
>>> odbchelper.__name__
'odbchelper'
Wiedząc o tym, możemy zaprojektować test wewnątrz swojego modułu, wykorzystując do tego instrukcję if. Jeśli uruchomisz bezpośrednio dany moduł, atrybut __name__ jest równy "__main__", a więc test zostanie wykonany. Podczas importu tego modułu, __name__ przyjmie inną wartość, więc test się nie uruchomi. Pomoże nam to rozwijać i wyszukiwać błędy w programie (czyli debugować), zanim dany moduł zintegrujemy z większym programem.
| Aby w MacPythonie można było skorzystać z tego triku, należy kliknąć w czarny trójkąt w prawym górnym rogu okna i upewnić się, że zaznaczona jest opcja Run as __main__. |
Materiały dodatkowe
[edytuj]- Python Reference Manual omawia szczegóły dotyczące importowania modułów, istnieje także polskie tłumaczenie.