Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out what methods, properties, etc a python module possesses

Tags:

python

import

Lets say I import a module. In order for me to make the best use of it, I would like to know what properties, methods, etc. that I can use. Is there a way to find that out?

As an example: Determining running programs in Python

In this line:

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

Let's say I wanted to also print out the memory consumed by the processes. How do I find out if that's possible? And what would be the correct 'label' for it? (just as the author uses 'Commandline', 'ProcessId')

Similarly, in this:

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 = '{0}'".format(name))     return len(colItems)  print find_process("SciTE.exe") 

How would I make the function also print out the memory consumed, the executable path, etc.?

like image 943
ldmvcd Avatar asked Feb 24 '11 10:02

ldmvcd


People also ask

How can I find the methods or attributes of an object in Python?

Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.

Which function is used to get all information about module in Python?

The dir() function The list contains the names of all the modules, variables, and functions that are defined in a module.


2 Answers

As for Python modules, you can do

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

and you'll get a list of supported methods (more exactly, you get the docstring, which might not contain every single method). If you want that, you can use

>>> dir(module) 

although now you'd just get a long list of all properties, methods, classes etc. in that module.

In your first example, you're calling an external program, though. Of course Python has no idea which features wmic.exe has. How should it?

like image 172
Tim Pietzcker Avatar answered Oct 05 '22 07:10

Tim Pietzcker


dir(module) returns the names of the attributes of the module

module.__dict__ is the mapping between the keys and the attributes objects themselves

module.__dict__.keys() and dir(module) are lists having the same elements, though they are not equals because the elements aren't in same order in them

it seems that help(module) iswhat you really need

like image 30
eyquem Avatar answered Oct 05 '22 07:10

eyquem