Home >Backend Development >Python Tutorial >How to Get a List of Imported Modules in Your Python Program?
Obtaining a Listing of Imported Modules
Need to compile a comprehensive list of all modules currently integrated into your Python program? Here's a simple approach:
<code class="python">import sys sys.modules.keys()</code>
With this method, you'll receive an array containing the names of all imported modules, such as ['os', 'sys'] for the example code below:
<code class="python">import os import sys</code>
Retrieving Imports for the Current Module
Occasionally, you may want to focus on obtaining a list of imports specific to the current module. While the above solution provides a comprehensive view of all imported modules, the following function offers a more targeted approach:
<code class="python">import types def imports(): for name, val in globals().items(): if isinstance(val, types.ModuleType): yield val.__name__</code>
Using this function, you'll retrieve a list of imported modules for the current module exclusively. However, it's worth noting that this approach excludes local imports and non-module imports (e.g., from x import y). Additionally, the function returns val.__name__, providing the original module name even if an alias was used (e.g., import module as alias). If you prefer to obtain the alias, replace yield val.__name__ with yield name.
The above is the detailed content of How to Get a List of Imported Modules in Your Python Program?. For more information, please follow other related articles on the PHP Chinese website!