Python узнать методы модуля

Как узнать, какими методами, свойствами и т. Д. Обладает модуль python?

Допустим, я импортирую модуль. Чтобы я мог наилучшим образом использовать его, я хотел бы знать, какие свойства, методы и т. Д. Я могу использовать. Есть ли способ узнать это?

os.system('WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid') 

Допустим, я хотел также распечатать память, занятую процессами. Как мне узнать, возможно ли это? И какой будет правильный «ярлык» для него? (так же, как автор использует ‘Commandline’, ‘ProcessId’)

import win32com.client def find_process(name): objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(".", "root\cimv2") colItems = objSWbemServices.ExecQuery( "Select * from Win32_Process where Caption = ''".format(name)) return len(colItems) print find_process("SciTE.exe") 

Как бы я заставил функцию также распечатать потребляемую память, путь к исполняемому файлу и т. Д.?

4 ответа

Что касается модулей Python, вы можете сделать

>>> import module >>> help(module) 

И вы получите список поддерживаемых методов (точнее, вы получите строку документации, которая может содержать не каждый метод). Если вы хотите, вы можете использовать

Хотя теперь вы просто получите длинный список всех свойств, методов, классов и т. д. в этом модуле.

В первом примере вы вызываете внешнюю программу. Конечно, Python не знает, какие функции есть у wmic.exe . Как это должно?

В Python есть встроенная функция dir (). Я не уверен, что это то, на что вы ссылаетесь, но запустите интерактивную консоль Python и введите:

import datetime dir(datetime) 

Это должно дать вам список методов, свойств и подмодулей

Хорошо, извините, я думаю, что вы новичок, и вы не понимаете, к каким фундаментальным понятиям я отношусь.

Объекты — это абстракция Python для данные. Все данные в программе Python представлены объектами или отношениями между объектами. http://docs.python.org/reference/datamodel.html # заместитель стандартного типа иерархии

Я не понимаю, почему это называется «абстракция»: для меня объект — это нечто реальное в машине, последовательность битов, организованных по определенным правилам для представления концептуальных данных или функционирования.

Имена относятся к объектам. Имена введены операции связывания имен. Каждое вхождение имени в текст программы относится к обязательному это имя установлено в глубине души функциональный блок, содержащий использование. http://docs.python.org/reference/executionmodel.html#naming и- связывающий

Пространство имен — это отображение имен объекты. В настоящее время большинство пространств имен реализовано в виде словарей Python , но это обычно не заметно в любым способом (кроме производительности) и это может измениться в будущем. Примеры из пространств имен: набор встроенных имена (содержащие функции, такие как abs () и встроенные имена исключений); глобальные имена в модуле; и локальные имена в вызове функции. В некотором смысле набор атрибутов Объект также образует пространство имен. http://docs.python.org/tutorial /classes.html#a-word-about-names-and-objects

Кстати, я использую слово атрибут для любого имени, следующего за точкой — для Например, в выражении z.real, real является атрибутом объекта z. Строго говоря, ссылки на имена в модулях есть ссылки на атрибуты: в выражении modname.funcname, modname является объектом модуля и funcname является его атрибутом. В в этом случае случается прямое отображение между атрибуты модуля и глобальные имена, определенные в модуле: они разделить одно и то же пространство имен! http://docs.python.org/tutorial /classes.html#a-word-about-names-and-objects

Пространство имен для модуля автоматически создается в первый раз Модуль импортирован. Основной модуль для скрипта всегда вызывается Основной . http://docs.python.org/reference/executionmodel.html#naming и- связывающий

Итак, программа на Python — это большая машина, которая играет с объектами, ссылками на эти объекты, именами этих объектов и пространствами имен, в которых связаны имена и объекты, пространства имен реализуются как словари.

Итак, вы правы: когда я ссылаюсь на ключи, я имею в виду имена, являющиеся ключами в различных пространствах имен. Имена являются произвольными или нет, в зависимости от того, являются ли объекты, которые они были созданы для именования, объектами пользователя или встроенными объектами.

Я советую вам внимательно прочитать части

dir(module) возвращает имена атрибутов модуля

module.__dict__ — это отображение между ключами и самими объектами атрибутов

module.__dict__.keys() и dir(module) являются списками, имеющими одинаковые элементы, хотя они не равны, поскольку элементы в них расположены не в том же порядке

Кажется, что > — это то, что вам действительно нужно

Источник

List All the Methods of a Python Module

List All the Methods of a Python Module

  1. List All the Methods of a Python Module Using the dir() Method
  2. List All the Methods of a Python Module Using the inspect() Module

A Python module, package, or library is a file or group of files containing definitions of Python functions, Python classes, and Python variables. In Python, we can import a module and use its implementations to stick with two important concepts of the world of computer science; Don’t reinvent the wheel and Don’t repeat yourself .

These packages or modules can be as small as a few lines and as big as millions of lines. As the size grows, it becomes difficult to analyze modules or see a clear outline of the content of the package. But Python developers have solved that problem for us as well.

In Python, there are many ways in which we can list down methods and classes of a Python module. In this article, we will talk about two such practices with the help of relevant examples. Note that, for instance, we will consider the NumPy Python module. If you don’t have the NumPy package on your system or virtual environment, you can download it using either the pip install numpy or the pip3 install numpy command.

List All the Methods of a Python Module Using the dir() Method

The dir() method is an in-built method in Python. It prints all the attributes and methods of an object or a Python package. Check the following code to understand it.

class A:  a = 10  b = 20  c = 200   def __init__(self, x):  self.x = x   def get_current_x(self):  return self.x   def set_x(self, x):  self.x = x   def __repr__(self):  return f"X: x>"  print(dir(int)) print(dir(float)) print(dir(A)) 
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] ['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real'] ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c', 'get_current_x', 'set_x'] 

We can use the dir() method to list down all the module methods. Refer to the following code to see how.

import numpy  print("NumPy Module") print(dir(numpy)) 

python list functions in module - the dir() method

As we can see, the dir() method has listed all the NumPy methods.

List All the Methods of a Python Module Using the inspect() Module

The inspect module is a Python module that has several helpful functions to get useful information about modules, classes, class objects, functions, tracebacks, and objects. We can use this module for our simple purpose. Refer to the following code to learn about its usage.

import numpy from inspect import getmembers, isfunction  print("NumPy Module") print(getmembers(numpy, isfunction)) 

python list functions in module - the inspect() method

  • ismodule() : Return True if the object is a module.
  • isclass() : Return True if the object is a class.
  • istraceback() : Return True if the object is a traceback.
  • isgenerator() : Return True if the object is a generator.
  • iscode() : Return True if the object is a code.
  • isframe() : Return True if the object is a frame.
  • isabstract() : Return True if the object is an abstract base class.
  • iscoroutine() : Return True if the object is a coroutine.

To learn more about this module, refer to the official documentation.

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article — Python Module

Источник

Читайте также:  Use environment variables in python
Оцените статью