En palabras simples, un módulo de python contiene funciones y declaraciones. Un módulo puede contener muchos elementos o definir funciones, clases, código ejecutable y variables también. A módulo puede ayudarlo a mantener el código relacionado colectivamente en algún lugar. En aspectos lógicos como también puedes mantener tu código organizado. Si usa editores y shell, habrá algunos módulos que estarán disponibles de forma predeterminada o integrada. Por lo tanto, vamos a ver muchas formas de obtener la lista de módulos de Python. ¡¡¡Vamos a rodar!!!
Creando un módulo de python simple
Crear un módulo de python es muy fácil. Como se discutió anteriormente, en un módulo puede definir funciones, clases e incluso variables. Tienes que escribir la función o el código ejecutable, guardar el archivo con .py extensión, impórtelo y utilícelo en el código. Tan sencillo como eso.
def welcome_message(name): print("Howdy" + name)
Bueno, hemos definido una función que saluda al nombre de entrada. Tenemos que guardar el archivo como un .py extensión. En este caso, lo vamos a guardar como mimodulo.py. Ahora podemos importar el módulo y llamar a la función.
import mymodule mymodule.welcome_message("Hackanons")
Howdy, Hackanons
Obtenga una lista de módulos en python (incorporado)
Crear un módulo es fácil como se muestra arriba. Pero python ofrece muchos de los módulos más útiles para sus propósitos de codificación. Si desea saber qué módulos le ofrece Python, puede ejecutar el siguiente código para obtener la lista de módulos en Python.
help('modules')
Cython brain_random mailcap sndhdr IPython brain_re markupsafe snowballstemmer OpenSSL brain_responses marshal socket PIL brain_scipy_signal math socketserver PyQt5 brain_six matplotlib socks __future__ brain_sqlalchemy mccabe sockshandler _abc brain_ssl menuinst sortedcollections _ast brain_subprocess mimetypes sortedcontainers _asyncio brain_threading mistune soupsieve _bisect brain_type mkl sphinx _black_version brain_typing mkl_fft sphinxcontrib _blake2 brain_uuid mkl_random spyder _bootlocale brotli mmap spyder_kernels _bz2 bs4 mmapfile sqlalchemy _cffi_backend builtins mmsystem sqlite3 _codecs bz2 mock sre_compile _codecs_cn cProfile modulefinder sre_constants _codecs_hk calendar more_itertools sre_parse _codecs_iso2022 certifi mpmath ssl _codecs_jp cffi msgpack sspi _codecs_kr cgi msilib sspicon _codecs_tw cgitb msvcrt stat _collections chardet multipledispatch statistics _collections_abc chunk multiprocessing statsmodels _compat_pickle click mymodule storemagic _compression cloudpickle mypy_extensions string _contextvars clyent nacl stringprep _csv cmath navigator_updater struct _ctypes cmd nbclient subprocess _ctypes_test code nbconvert sunau _datetime codecs nbformat symbol _decimal codeop nest_asyncio sympy _distutils_hack collections netbios sympyprinting _dummy_thread colorama netrc symtable _elementtree colorsys networkx sys _functools commctrl nltk sysconfig _hashlib compileall nntplib tables _heapq comtypes nose tabnanny _imp concurrent notebook tarfile _io conda nt tblib _json conda_build ntpath telnetlib _locale conda_env ntsecuritycon tempfile _lsprof conda_package_handling nturl2path terminado _lzma conda_verify numba test _markupbase configparser numbers test_data _md5 contextlib numexpr test_pycosat _msi contextlib2 numpy testpath _multibytecodec contextvars numpydoc tests _multiprocessing copy odbc textdistance _nsis copyreg olefile textwrap _opcode crypt opcode this _operator cryptography openpyxl threading _osx_support csv operator threadpoolctl _overlapped ctypes optparse three_merge _pickle curl os tifffile _py_abc curses packaging time _pydecimal cwp pandas timeit _pyio cycler pandocfilters timer _pyrsistent_version cython paramiko tkinter _pytest cythonmagic parser tlz _queue cytoolz parso token _random dask partd tokenize _sha1 dataclasses past toml _sha256 datetime path toolz _sha3 dateutil pathlib tornado _sha512 dbi pathlib2 tqdm _signal dbm pathspec trace _sitebuiltins dde pathtools traceback _socket decimal patsy tracemalloc _sqlite3 decorator pdb traitlets _sre defusedxml pep8 tty _ssl diff_match_patch perfmon turtle _stat difflib pexpect turtledemo _statistics dis pickle typed_ast _string distributed pickleshare types _strptime distutils pickletools typing _struct doctest pip typing_extensions _symtable docutils pipes ujson _system_path dummy_threading pkg_resources unicodecsv _testbuffer email pkginfo unicodedata _testcapi encodings pkgutil unittest _testconsole ensurepip platform urllib _testimportmultiple entrypoints plistlib urllib3 _testinternalcapi enum pluggy uu _testmultiphase erfa ply uuid _thread errno poplib venv _threading_local et_xmlfile posixpath warnings _tkinter fastcache pprint watchdog _tracemalloc faulthandler profile wave _warnings filecmp prometheus_client wcwidth _weakref fileinput prompt_toolkit weakref _weakrefset filelock pstats webbrowser _win32sysloader flake8 psutil webencodings _winapi flask pty werkzeug _winxptheme fnmatch ptyprocess wheel _xxsubinterpreters formatter pvectorc widgetsnbextension _yaml fractions py win2kras abc fsspec py_compile win32api adodbapi ftplib pyclbr win32clipboard afxres functools pycodestyle win32com aifc future pycosat win32con alabaster gc pycparser win32console anaconda_navigator genericpath pycurl win32cred anaconda_project getopt pydoc win32crypt antigravity getpass pydoc_data win32cryptcon appdirs gettext pydocstyle win32ctypes argh gevent pyexpat win32event argon2 glob pyflakes win32evtlog argparse glob2 pygments win32evtlogutil array gmpy2 pylab win32file asn1crypto greenlet pylint win32gui ast gzip pyls win32gui_struct astroid h5py pyls_black win32help astropy hashlib pyls_jsonrpc win32inet async_generator heapdict pyls_spyder win32inetcon asynchat heapq pyodbc win32job asyncio hmac pyparsing win32lz asyncore html pyreadline win32net atexit html5lib pyrsistent win32netcon atomicwrites http pytest win32pdh attr idlelib pythoncom win32pdhquery audioop idna pytz win32pdhutil autopep8 imageio pywin win32pipe autoreload imagesize pywin32_bootstrap win32print babel imaplib pywin32_testutil win32process backcall imghdr pywintypes win32profile backports imp pywt win32ras base64 importlib pyximport win32rcparser bcrypt importlib_metadata qdarkstyle win32security bdb iniconfig qtawesome win32service binascii inspect qtconsole win32serviceutil binhex intervaltree qtpy win32timezone binstar_client io queue win32trace bisect ipaddress quopri win32traceutil bitarray ipykernel random win32transaction bkcharts ipykernel_launcher rasutil win32ts black ipython_genutils re win32ui blackd ipywidgets readline win32uiole bleach isapi regcheck win32verstamp blib2to3 isort regex win32wnet
Eso es todo. El comando de ayuda obtendrá una lista de módulos de python que están disponibles para usar en el código.
Lista de módulos de python en el entorno Conda
¿Utilizas el navegador Anaconda? En caso afirmativo, debe abrir el indicador de conda y luego ejecutar el “lista de condas” comando para obtener la lista de módulos disponibles en python.
conda list
Con la ayuda de “lista de condas” comando, obtendrá la lista de módulos con su versión actual e información de compilación.
Beneficios de los módulos de Python
- Puede crear un código organizado lógicamente con todas las funciones y declaraciones relacionadas en un archivo, es decir, un módulo.
- Aumentará la legibilidad del código para una fácil comprensión.
- La función definida puede reutilizarse cuando sea necesario.
- Ayudará a evitar la duplicidad del código.
Terminando
Python por defecto ofrece muchos módulos para su viaje de codificación. Puede crear fácilmente sus módulos personalizados según sus requisitos. Si lo desea, puede obtener la lista de módulos de Python con la ayuda del código que se muestra arriba. Puede usar diferentes métodos como se ilustra en este artículo. ¡¡¡Feliz pitón!!!.