import sys
sys.modules.keys()

An approximation of getting all imports for the current module only would be to inspect globals() for modules:

import types
def imports():
    for name, val in globals().items():
        if isinstance(val, types.ModuleType):
            yield val.__name__

This won't return local imports, or non-module imports like from x import y. Note that this returns val.__name__ so you get the original module name if you used import module as alias; yield name instead if you want the alias.

Answer from Glenn Maynard on Stack Overflow
🌐
PyPI
pypi.org › project › findimports
findimports
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Python
docs.python.org › 3 › library › modulefinder.html
modulefinder — Find modules used by a script
from modulefinder import ModuleFinder finder = ModuleFinder() finder.run_script('bacon.py') print('Loaded modules:') for name, mod in finder.modules.items(): print('%s: ' % name, end='') print(','.join(list(mod.globalnames.keys())[:3])) print('-'*50) print('Modules not imported:') print('\n'.join(finder.badmodules.keys())) Sample output (may vary depending on the architecture): Loaded modules: _types: copyreg: _inverted_registry,_slotnames,__all__ re._compiler: isstring,_sre,_optimize_unicode _sre: re._constants: REPEAT_ONE,makedict,AT_END_LINE sys: re: __module__,finditer,_expand itertools: __main__: re,itertools,baconhameggs re._parser: _PATTERNENDERS,SRE_FLAG_UNICODE array: types: __module__,IntType,TypeType --------------------------------------------------- Modules not imported: guido.python.ham baconhameggs
Discussions

linux - Get all modules/packages used by a python project - Stack Overflow
It contains all the imports libraries with versions you are using in the virtualenv or in the python correctly installed. Just type: pip install pipreqs pipreqs /home/project/location More on stackoverflow.com
🌐 stackoverflow.com
python - How to find all imports placed in the code? - Stack Overflow
Our project contains a lot of import statements inside class/function. That was the way to overcome cycle import issue at the moment. And for now we want to research and fix design issue behind it.... More on stackoverflow.com
🌐 stackoverflow.com
How to get a list of available imports (modules or libraries available in your device)?
That's not possible, or at least not easily possible. Python doesn't actually discover modules until you ask it for one using import. More on reddit.com
🌐 r/learnpython
6
1
June 6, 2020
List of all imports in python 3 - Stack Overflow
How to find out list of all available imports in python 3 via program? I tried this at first, but couldn't understand what it returned import sys sys.modules I think this isn't the way, although More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 4
148

You can give a try to the library https://github.com/bndr/pipreqs found following the guide https://www.fullstackpython.com/application-dependencies.html


The library pipreqs is pip installable and automatically generates the file requirements.txt.

It contains all the imports libraries with versions you are using in the virtualenv or in the python correctly installed. Just type:

pip install pipreqs
pipreqs /home/project/location

It will print:

INFO: Successfully saved requirements file in /home/project/location/requirements.txt

In addition it is compatible with the pip install -r command: if you need to create a venv of your project, or update your current python version with compatible libraries, you just need to type:

pip install -r requirements.txt

I had the same problem and this library solved it for me. Not sure if it works for multiple layers of dependencies i.e. in case you have nested level of dependent libraries.


Edit 1:

pipreqs is the bare and direct solution working quickly on any python environment.

If looking for a more sophisticated version manager, please consider as well pyvenv https://github.com/pyenv/pyenv. It wraps virtualenv producing some improvements over the version specification that is created by pipreqs.


Edit 2:

If, after creating the file with the dependency libraries of your module with pipreqs, you want to pin the whole dependency tree (not just the top level of dependencies), take a look at pip-compile. It figures out a way to get all the dependencies of your top level libraries, and it pins them in a new requirement files, so creating the full dependency tree.


Edit 3:

If you want to split your dependency tree into different files (e.g. base, test, dev, docs) and have a way of managing the dependency tree, please take a look at pip-compile-multi.


Edit 4:

pip-compile and pip-compile-multi are also bare and direct solutions to create the dependency tree of a project, that can be then installed on any environment of choice.

The divide between the dependency tree tool management and the environment can be positive or negative. For example it is easy to generate the dependency tree in the requirement files, and then forget to install them with the chosen interpreter, having then an environment that is silently out of synch with the requirements files.

There are further solutions combining the dependency management and the python interpreter, and the install manager in one single tool, with added bonus of optimisations. If this direction is appealing, I would recommend taking a look at:

  • poetry
  • PDM
  • Hatch
  • uv

and start projects directly with one of these dependency manager (if you wonder were to start, uv is my favourite, as the learning curve is minimal, it is compatible with any other tool you are probably already using making the upgrade seamless, and it is really fast, though they are all valid options).

2 of 4
2

Install yolk for python2 with:

pip install yolk

Or install yolk for python3 with:

pip install yolk3k

Call the following to get the list of eggs in your environment:

yolk -l

Alternatively, you can use snakefood for graphing your dependencies, as answered in this question.

You could try going into the site-packages folder where the unpacked eggs are stored, and running this:

ls -l */LICENSE*

That will give you a list of the licence files for each project (if they're stored in the root of the egg, which they usually are).

🌐
Stack Overflow
stackoverflow.com › questions › 71924129 › how-to-find-all-imports-placed-in-the-code
python - How to find all imports placed in the code? - Stack Overflow
You can try to quickly make your own search tool using python / ReGex ... Otherwise you can create your own librairy importer ... since the statements you're looking for are inside functions or methods, they will be preceded by at least one space. So just do a regex search in your ide for " +.*import". (or with e.g. grep: grep -E -C 3 -n '^ +.*import' **.py) ... Use pipreqs. Running pipreqs with the default arguments will generate a requirements.txt for you. $ pipreqs /home/project/location Successfully saved requirements file in /home/project/location/requirements.txt
🌐
GitHub
gist.github.com › lrq3000 › 6175522
List recursively all imports of modules along with versions done from your Python application. Tested on Python 2.7. No dependencies except standard Python libs. · GitHub
List recursively all imports of modules along with versions done from your Python application. Tested on Python 2.7. No dependencies except standard Python libs. - pylistmodules.py
🌐
GitHub
github.com › ericdill › depfinder
GitHub - ericdill/depfinder: Find all the unique imports in your library
December 14, 2021 - $ depfinder -h usage: depfinder [-h] [-y] [-V] [--no-remap] [-v] [-q] [-k KEY] [--conda] [--pdb] file_or_directory Tool for inspecting the dependencies of your python project. positional arguments: file_or_directory Valid options are a single python file, a single jupyter (ipython) notebook or a directory of files that include python files optional arguments: -h, --help show this help message and exit -y, --yaml Output in syntactically valid yaml when true. Defaults to False -V, --version Print out the version of depfinder and exit --no-remap Do not remap the names of the imported libraries to their proper conda name -v, --verbose Enable debug level logging info from depfinder -q, --quiet Turn off all logging from depfinder -k KEY, --key KEY Select some or all of the output keys.
Starred by 41 users
Forked by 10 users
Languages   Python 94.2% | Jupyter Notebook 5.8% | Python 94.2% | Jupyter Notebook 5.8%
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › how to get a list of available imports (modules or libraries available in your device)?
r/learnpython on Reddit: How to get a list of available imports (modules or libraries available in your device)?
June 6, 2020 -

Some solutions are calling help('modules') and using a command line. But I want a list (the list structure) of all available imports. How can I do this?

Actually, what I’m trying to do is explore what libraries are available on Pythonista 3 (an iOS Python IDE). I want to get a list of modules excluding those from the standard library so I can print out each module’s docstring.

Top answer
1 of 6
5

From http://docs.python.org/library/sys.html (a good place to look for documentation on python stdlib)

sys.builtin_module_names

is a tuple (a bit like a immutable anonymous structs) of strings giving the names of all modules that are compiled into this Python interpreter.

sys.modules

This is a dictionary that maps module names to modules (module objects) which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.

So modules is a dictionary (a mapping of module names to the actual module objects). To get just the names type sys.modules.keys() although it probably isn't that usefull.

2 of 6
4

Worked as with the Python 2 and the Python 3 (tested with the next version of the 2.7, 3.4, 3.5)

import shutil
import pkgutil

def show_acceptable_modules():
    line = '-' * 100
    print('{}\n{:^30}|{:^20}\n{}'.format(line, 'Module', 'Location', line))
    for entry in pkgutil.iter_modules():
        print('{:30}| {}'.format(entry[1], entry[0].path))

Sample output for the Python 2.7

>>> show_acceptable_modules()
----------------------------------------------------------------------------------------------------
            Module            |      Location      
----------------------------------------------------------------------------------------------------
ANSI                          | /usr/lib/python2.7/dist-packages
BaseHTTPServer                | /usr/lib/python2.7
Bastion                       | /usr/lib/python2.7
CDROM                         | /usr/lib/python2.7/plat-x86_64-linux-gnu
CGIHTTPServer                 | /usr/lib/python2.7
Canvas                        | /usr/lib/python2.7/lib-tk
ConfigParser                  | /usr/lib/python2.7
Cookie                        | /usr/lib/python2.7
DLFCN                         | /usr/lib/python2.7/plat-x86_64-linux-gnu
Dialog                        | /usr/lib/python2.7/lib-tk
DocXMLRPCServer               | /usr/lib/python2.7
FSM                           | /usr/lib/python2.7/dist-packages
FileDialog                    | /usr/lib/python2.7/lib-tk
FixTk                         | /usr/lib/python2.7/lib-tk
HTMLParser                    | /usr/lib/python2.7
IN                            | /usr/lib/python2.7/plat-x86_64-linux-gnu
Image                         | /usr/lib/python2.7/dist-packages/PILcompat
ImageChops                    | /usr/lib/python2.7/dist-packages/PILcompat
ImageColor                    | /usr/lib/python2.7/dist-packages/PILcompat
ImageCrackCode                | /usr/lib/python2.7/dist-packages/PILcompat
ImageDraw                     | /usr/lib/python2.7/dist-packages/PILcompat
ImageEnhance                  | /usr/lib/python2.7/dist-packages/PILcompat
ImageFile                     | /usr/lib/python2.7/dist-packages/PILcompat
ImageFileIO                   | /usr/lib/python2.7/dist-packages/PILcompat
ImageFilter                   | /usr/lib/python2.7/dist-packages/PILcompat
ImageFont                     | /usr/lib/python2.7/dist-packages/PILcompat
ImageGL                       | /usr/lib/python2.7/dist-packages/PILcompat
ImageGrab                     | /usr/lib/python2.7/dist-packages/PILcompat
ImageMath                     | /usr/lib/python2.7/dist-packages/PILcompat
ImageOps                      | /usr/lib/python2.7/dist-packages/PILcompat
ImagePalette                  | /usr/lib/python2.7/dist-packages/PILcompat
ImagePath                     | /usr/lib/python2.7/dist-packages/PILcompat
ImageQt                       | /usr/lib/python2.7/dist-packages/PILcompat
ImageSequence                 | /usr/lib/python2.7/dist-packages/PILcompat
ImageStat                     | /usr/lib/python2.7/dist-packages/PILcompat
ImageTk                       | /usr/lib/python2.7/dist-packages/PILcompat
ImageWin                      | /usr/lib/python2.7/dist-packages/PILcompat
MimeWriter                    | /usr/lib/python2.7
ORBit                         | /usr/lib/pymodules/python2.7
PIL                           | /usr/lib/python2.7/dist-packages
PSDraw                        | /usr/lib/python2.7/dist-packages/PILcompat
PngImagePlugin                | /usr/lib/python2.7/dist-packages/PILcompat
Queue                         | /usr/lib/python2.7
SOAPpy                        | /usr/lib/python2.7/dist-packages
ScrolledText                  | /usr/lib/python2.7/lib-tk
SimpleDialog                  | /usr/lib/python2.7/lib-tk
SimpleHTTPServer              | /usr/lib/python2.7
SimpleXMLRPCServer            | /usr/lib/python2.7
SocketServer                  | /usr/lib/python2.7
StringIO                      | /usr/lib/python2.7
TYPES                         | /usr/lib/python2.7/plat-x86_64-linux-gnu
Tix                           | /usr/lib/python2.7/lib-tk
Tkconstants                   | /usr/lib/python2.7/lib-tk
Tkdnd                         | /usr/lib/python2.7/lib-tk
Tkinter                       | /usr/lib/python2.7/lib-tk
UserDict                      | /usr/lib/python2.7
UserList                      | /usr/lib/python2.7
UserString                    | /usr/lib/python2.7
_LWPCookieJar                 | /usr/lib/python2.7
_MozillaCookieJar             | /usr/lib/python2.7
__future__                    | /usr/lib/python2.7
_abcoll                       | /usr/lib/python2.7
_bsddb                        | /usr/lib/python2.7/lib-dynload
_codecs_cn                    | /usr/lib/python2.7/lib-dynload
_codecs_hk                    | /usr/lib/python2.7/lib-dynload
_codecs_iso2022               | /usr/lib/python2.7/lib-dynload
_codecs_jp                    | /usr/lib/python2.7/lib-dynload
_codecs_kr                    | /usr/lib/python2.7/lib-dynload
_codecs_tw                    | /usr/lib/python2.7/lib-dynload
_csv                          | /usr/lib/python2.7/lib-dynload
_ctypes                       | /usr/lib/python2.7/lib-dynload
_ctypes_test                  | /usr/lib/python2.7/lib-dynload
_curses                       | /usr/lib/python2.7/lib-dynload
_curses_panel                 | /usr/lib/python2.7/lib-dynload
_dbus_bindings                | /usr/lib/python2.7/dist-packages
_dbus_glib_bindings           | /usr/lib/python2.7/dist-packages
_elementtree                  | /usr/lib/python2.7/lib-dynload
_hashlib                      | /usr/lib/python2.7/lib-dynload
_hotshot                      | /usr/lib/python2.7/lib-dynload
_json                         | /usr/lib/python2.7/lib-dynload
_lsprof                       | /usr/lib/python2.7/lib-dynload
_multibytecodec               | /usr/lib/python2.7/lib-dynload
_multiprocessing              | /usr/lib/python2.7/lib-dynload
_osx_support                  | /usr/lib/python2.7
_pyio                         | /usr/lib/python2.7
_smbc                         | /usr/lib/python2.7/dist-packages
_sqlite3                      | /usr/lib/python2.7/lib-dynload
_ssl                          | /usr/lib/python2.7/lib-dynload
_strptime                     | /usr/lib/python2.7
_sysconfigdata                | /usr/lib/python2.7
_sysconfigdata_nd             | /usr/lib/python2.7/plat-x86_64-linux-gnu
_testcapi                     | /usr/lib/python2.7/lib-dynload
_threading_local              | /usr/lib/python2.7
_weakrefset                   | /usr/lib/python2.7
abc                           | /usr/lib/python2.7
aifc                          | /usr/lib/python2.7
antigravity                   | /usr/lib/python2.7
anydbm                        | /usr/lib/python2.7
apt                           | /usr/lib/python2.7/dist-packages
apt_inst                      | /usr/lib/python2.7/dist-packages
apt_pkg                       | /usr/lib/python2.7/dist-packages
aptsources                    | /usr/lib/python2.7/dist-packages
argparse                      | /usr/lib/python2.7
ast                           | /usr/lib/python2.7
asynchat                      | /usr/lib/python2.7
asyncore                      | /usr/lib/python2.7
atexit                        | /usr/lib/python2.7
atk                           | /usr/lib/python2.7/dist-packages/gtk-2.0
audiodev                      | /usr/lib/python2.7
audioop                       | /usr/lib/python2.7/lib-dynload
base64                        | /usr/lib/python2.7
bdb                           | /usr/lib/python2.7
binhex                        | /usr/lib/python2.7
bisect                        | /usr/lib/python2.7
bonobo                        | /usr/lib/python2.7/dist-packages/gtk-2.0
bsddb                         | /usr/lib/python2.7
bz2                           | /usr/lib/python2.7/lib-dynload
cProfile                      | /usr/lib/python2.7
cairo                         | /usr/lib/pymodules/python2.7
calendar                      | /usr/lib/python2.7
caribou                       | /usr/lib/python2.7/dist-packages
cgi                           | /usr/lib/python2.7
cgitb                         | /usr/lib/python2.7
chardet                       | /usr/lib/python2.7/dist-packages
chunk                         | /usr/lib/python2.7
cmd                           | /usr/lib/python2.7
code                          | /usr/lib/python2.7
codecs                        | /usr/lib/python2.7
codeop                        | /usr/lib/python2.7
collections                   | /usr/lib/python2.7
colorlog                      | /usr/lib/python2.7/dist-packages
colorsys                      | /usr/lib/python2.7
commands                      | /usr/lib/python2.7
compileall                    | /usr/lib/python2.7
compiler                      | /usr/lib/python2.7
contextlib                    | /usr/lib/python2.7
cookielib                     | /usr/lib/python2.7
copy                          | /usr/lib/python2.7
copy_reg                      | /usr/lib/python2.7
crypt                         | /usr/lib/python2.7/lib-dynload
csv                           | /usr/lib/python2.7
ctypes                        | /usr/lib/python2.7
cups                          | /usr/lib/python2.7/dist-packages
cupsext                       | /usr/lib/python2.7/dist-packages
cupshelpers                   | /usr/lib/python2.7/dist-packages
curl                          | /usr/lib/python2.7/dist-packages
curses                        | /usr/lib/python2.7
dbhash                        | /usr/lib/python2.7
dbm                           | /usr/lib/python2.7/lib-dynload
dbus                          | /usr/lib/python2.7/dist-packages
deb822                        | /usr/lib/python2.7/dist-packages
debconf                       | /usr/lib/python2.7/dist-packages
debian                        | /usr/lib/python2.7/dist-packages
debian_bundle                 | /usr/lib/python2.7/dist-packages
debianbts                     | /usr/lib/pymodules/python2.7
decimal                       | /usr/lib/python2.7
defusedxml                    | /usr/lib/python2.7/dist-packages
difflib                       | /usr/lib/python2.7
dircache                      | /usr/lib/python2.7
dis                           | /usr/lib/python2.7
distutils                     | /usr/lib/python2.7
doctest                       | /usr/lib/python2.7
docutils                      | /usr/lib/python2.7/dist-packages
drv_libxml2                   | /usr/lib/python2.7/dist-packages
dsextras                      | /usr/lib/python2.7/dist-packages/gtk-2.0
dumbdbm                       | /usr/lib/python2.7
dummy_thread                  | /usr/lib/python2.7
dummy_threading               | /usr/lib/python2.7
email                         | /usr/lib/python2.7
encodings                     | /usr/lib/python2.7
ensurepip                     | /usr/lib/python2.7
fdpexpect                     | /usr/lib/python2.7/dist-packages
filecmp                       | /usr/lib/python2.7
fileinput                     | /usr/lib/python2.7
fnmatch                       | /usr/lib/python2.7
formatter                     | /usr/lib/python2.7
fpectl                        | /usr/lib/python2.7/lib-dynload
fpformat                      | /usr/lib/python2.7
fractions                     | /usr/lib/python2.7
ftplib                        | /usr/lib/python2.7
functools                     | /usr/lib/python2.7
future_builtins               | /usr/lib/python2.7/lib-dynload
gconf                         | /usr/lib/python2.7/dist-packages/gtk-2.0
genericpath                   | /usr/lib/python2.7
getopt                        | /usr/lib/python2.7
getpass                       | /usr/lib/python2.7
gettext                       | /usr/lib/python2.7
gi                            | /usr/lib/python2.7/dist-packages
gio                           | /usr/lib/python2.7/dist-packages/gtk-2.0
glib                          | /usr/lib/python2.7/dist-packages
glob                          | /usr/lib/python2.7
gnome                         | /usr/lib/python2.7/dist-packages/gtk-2.0
gnomecanvas                   | /usr/lib/python2.7/dist-packages/gtk-2.0
gnomevfs                      | /usr/lib/python2.7/dist-packages/gtk-2.0
gobject                       | /usr/lib/python2.7/dist-packages
gtk                           | /usr/lib/python2.7/dist-packages/gtk-2.0
gtkunixprint                  | /usr/lib/python2.7/dist-packages/gtk-2.0
gtweak                        | /usr/lib/python2.7/dist-packages
guake                         | /usr/lib/python2.7/dist-packages
gzip                          | /usr/lib/python2.7
hamster                       | /usr/lib/python2.7/dist-packages
hashlib                       | /usr/lib/python2.7
heapq                         | /usr/lib/python2.7
hgext                         | /usr/lib/python2.7/dist-packages
hmac                          | /usr/lib/python2.7
hotshot                       | /usr/lib/python2.7
hpmudext                      | /usr/lib/python2.7/dist-packages
htmlentitydefs                | /usr/lib/python2.7
htmllib                       | /usr/lib/python2.7
httplib                       | /usr/lib/python2.7
ihooks                        | /usr/lib/python2.7
imaplib                       | /usr/lib/python2.7
imghdr                        | /usr/lib/python2.7
importlib                     | /usr/lib/python2.7
imputil                       | /usr/lib/python2.7
inspect                       | /usr/lib/python2.7
io                            | /usr/lib/python2.7
json                          | /usr/lib/python2.7
keyword                       | /usr/lib/python2.7
lib2to3                       | /usr/lib/python2.7
libxml2                       | /usr/lib/python2.7/dist-packages
libxml2mod                    | /usr/lib/python2.7/dist-packages
linecache                     | /usr/lib/python2.7
linuxaudiodev                 | /usr/lib/python2.7/lib-dynload
locale                        | /usr/lib/python2.7
logging                       | /usr/lib/python2.7
lsb_release                   | /usr/lib/python2.7/dist-packages
lxml                          | /usr/lib/python2.7/dist-packages
macpath                       | /usr/lib/python2.7
macurl2path                   | /usr/lib/python2.7
mailbox                       | /usr/lib/python2.7
mailcap                       | /usr/lib/python2.7
markupbase                    | /usr/lib/python2.7
md5                           | /usr/lib/python2.7
mercurial                     | /usr/lib/python2.7/dist-packages
mhlib                         | /usr/lib/python2.7
mimetools                     | /usr/lib/python2.7
mimetypes                     | /usr/lib/python2.7
mimify                        | /usr/lib/python2.7
mmap                          | /usr/lib/python2.7/lib-dynload
modulefinder                  | /usr/lib/python2.7
multifile                     | /usr/lib/python2.7
multiprocessing               | /usr/lib/python2.7
mutex                         | /usr/lib/python2.7
ndiff                         | /usr/lib/python2.7/dist-packages
netrc                         | /usr/lib/python2.7
new                           | /usr/lib/python2.7
nis                           | /usr/lib/python2.7/lib-dynload
nntplib                       | /usr/lib/python2.7
ntpath                        | /usr/lib/python2.7
nturl2path                    | /usr/lib/python2.7
numbers                       | /usr/lib/python2.7
numpy                         | /usr/lib/python2.7/dist-packages
opcode                        | /usr/lib/python2.7
optparse                      | /usr/lib/python2.7
os                            | /usr/lib/python2.7
os2emxpath                    | /usr/lib/python2.7
ossaudiodev                   | /usr/lib/python2.7/lib-dynload
pango                         | /usr/lib/python2.7/dist-packages/gtk-2.0
pangocairo                    | /usr/lib/python2.7/dist-packages/gtk-2.0
parser                        | /usr/lib/python2.7/lib-dynload
pcardext                      | /usr/lib/python2.7/dist-packages
pdb                           | /usr/lib/python2.7
pexpect                       | /usr/lib/python2.7/dist-packages
pickle                        | /usr/lib/python2.7
pickletools                   | /usr/lib/python2.7
pipes                         | /usr/lib/python2.7
pkg_resources                 | /usr/lib/python2.7/dist-packages
pkgutil                       | /usr/lib/python2.7
platform                      | /usr/lib/python2.7
plistlib                      | /usr/lib/python2.7
popen2                        | /usr/lib/python2.7
poplib                        | /usr/lib/python2.7
posixfile                     | /usr/lib/python2.7
posixpath                     | /usr/lib/python2.7
pprint                        | /usr/lib/python2.7
profile                       | /usr/lib/python2.7
pstats                        | /usr/lib/python2.7
pty                           | /usr/lib/python2.7
pxssh                         | /usr/lib/python2.7/dist-packages
py_compile                    | /usr/lib/python2.7
pyatspi                       | /usr/lib/python2.7/dist-packages
pyclbr                        | /usr/lib/python2.7
pycurl                        | /usr/lib/python2.7/dist-packages
pydoc                         | /usr/lib/python2.7
pydoc_data                    | /usr/lib/python2.7
pyexpat                       | /usr/lib/python2.7/lib-dynload
pygments                      | /usr/lib/python2.7/dist-packages
pygtk                         | /usr/lib/python2.7/dist-packages
pygtkcompat                   | /usr/lib/python2.7/dist-packages
pynotify                      | /usr/lib/python2.7/dist-packages/gtk-2.0
quopri                        | /usr/lib/python2.7
random                        | /usr/lib/python2.7
re                            | /usr/lib/python2.7
readline                      | /usr/lib/python2.7/lib-dynload
reportbug                     | /usr/lib/python2.7/dist-packages
reportlab                     | /usr/lib/python2.7/dist-packages
repr                          | /usr/lib/python2.7
resource                      | /usr/lib/python2.7/lib-dynload
rexec                         | /usr/lib/python2.7
rfc822                        | /usr/lib/python2.7
rlcompleter                   | /usr/lib/python2.7
robotparser                   | /usr/lib/python2.7
roman                         | /usr/lib/python2.7/dist-packages
runpy                         | /usr/lib/python2.7
scanext                       | /usr/lib/python2.7/dist-packages
sched                         | /usr/lib/python2.7
screen                        | /usr/lib/python2.7/dist-packages
sets                          | /usr/lib/python2.7
sgmllib                       | /usr/lib/python2.7
sha                           | /usr/lib/python2.7
shelve                        | /usr/lib/python2.7
shlex                         | /usr/lib/python2.7
shutil                        | /usr/lib/python2.7
site                          | /usr/lib/python2.7
sitecustomize                 | /usr/lib/python2.7
six                           | /usr/lib/python2.7/dist-packages
smbc                          | /usr/lib/python2.7/dist-packages
smtpd                         | /usr/lib/python2.7
smtplib                       | /usr/lib/python2.7
sndhdr                        | /usr/lib/python2.7
socket                        | /usr/lib/python2.7
sqlite3                       | /usr/lib/python2.7
sre                           | /usr/lib/python2.7
sre_compile                   | /usr/lib/python2.7
sre_constants                 | /usr/lib/python2.7
sre_parse                     | /usr/lib/python2.7
ssl                           | /usr/lib/python2.7
stat                          | /usr/lib/python2.7
statvfs                       | /usr/lib/python2.7
string                        | /usr/lib/python2.7
stringold                     | /usr/lib/python2.7
stringprep                    | /usr/lib/python2.7
struct                        | /usr/lib/python2.7
subprocess                    | /usr/lib/python2.7
sunau                         | /usr/lib/python2.7
sunaudio                      | /usr/lib/python2.7
symbol                        | /usr/lib/python2.7
symtable                      | /usr/lib/python2.7
sysconfig                     | /usr/lib/python2.7
tabnanny                      | /usr/lib/python2.7
talloc                        | /usr/lib/python2.7/dist-packages
tarfile                       | /usr/lib/python2.7
telnetlib                     | /usr/lib/python2.7
tempfile                      | /usr/lib/python2.7
termios                       | /usr/lib/python2.7/lib-dynload
test                          | /usr/lib/python2.7
textwrap                      | /usr/lib/python2.7
this                          | /usr/lib/python2.7
threading                     | /usr/lib/python2.7
timeit                        | /usr/lib/python2.7
tkColorChooser                | /usr/lib/python2.7/lib-tk
tkCommonDialog                | /usr/lib/python2.7/lib-tk
tkFileDialog                  | /usr/lib/python2.7/lib-tk
tkFont                        | /usr/lib/python2.7/lib-tk
tkMessageBox                  | /usr/lib/python2.7/lib-tk
tkSimpleDialog                | /usr/lib/python2.7/lib-tk
toaiff                        | /usr/lib/python2.7
token                         | /usr/lib/python2.7
tokenize                      | /usr/lib/python2.7
trace                         | /usr/lib/python2.7
traceback                     | /usr/lib/python2.7
ttk                           | /usr/lib/python2.7/lib-tk
tty                           | /usr/lib/python2.7
turtle                        | /usr/lib/python2.7/lib-tk
types                         | /usr/lib/python2.7
unittest                      | /usr/lib/python2.7
urllib                        | /usr/lib/python2.7
urllib2                       | /usr/lib/python2.7
urlparse                      | /usr/lib/python2.7
user                          | /usr/lib/python2.7
uu                            | /usr/lib/python2.7
uuid                          | /usr/lib/python2.7
vboxapi                       | /usr/lib/python2.7/dist-packages
vte                           | /usr/lib/python2.7/dist-packages/gtk-2.0
warnings                      | /usr/lib/python2.7
wave                          | /usr/lib/python2.7
weakref                       | /usr/lib/python2.7
webbrowser                    | /usr/lib/python2.7
whichdb                       | /usr/lib/python2.7
wnck                          | /usr/lib/python2.7/dist-packages/gtk-2.0
wsgiref                       | /usr/lib/python2.7
wstools                       | /usr/lib/python2.7/dist-packages
xdg                           | /usr/lib/python2.7/dist-packages
xdrlib                        | /usr/lib/python2.7
xml                           | /usr/lib/python2.7
xmllib                        | /usr/lib/python2.7
xmlrpclib                     | /usr/lib/python2.7
zeitgeist                     | /usr/lib/python2.7/dist-packages
zipfile                       | /usr/lib/python2.7

Testing environment

$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 8.6 (jessie)
Release:    8.6
Codename:   jessie
$ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
$ python2 --version
Python 2.7.9
$ python3.4 --version
Python 3.4.2
$ python3.5 --version
Python 3.5.2
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 easy ways to list imported modules in python
5 Easy Ways to List Imported Modules in Python - Be on the Right Side of Change
May 4, 2022 - Your imported global module names and versions may differ from that shown below. This example uses the sys library with List Comprenehsion to return all imported local module names, by default, in an unsorted list.
🌐
Python documentation
docs.python.org › 3 › reference › import.html
5. The import system — Python 3.14.4 documentation
Entries in sys.path can name directories on the file system, zip files, and potentially other “locations” (see the site module) that should be searched for modules, such as URLs, or database queries. Only strings should be present on sys.path; all other data types are ignored. The path based finder is a meta path finder, so the import machinery begins the import path search by calling the path based finder’s find_spec() method as described previously.
🌐
TutorialsPoint
tutorialspoint.com › How-to-find-which-Python-modules-are-being-imported-from-a-package
How to find which Python modules are being imported from a package?
The list of imported Python modules ... '/usr/lib64/python3.6/stat.py'>) The list of imported Python modules are : ('sys', <module 'sys' (built-in)>) The sys.modules dict can be used to discover all the Python modules from a specific package that are being utilised by an applica...
🌐
Xah Lee
xahlee.info › python › standard_modules.html
Python: List Modules, List Loaded Modules
October 10, 2022 - To list all available modules in module path, type ... (on Microsoft Windows, pydoc is at C:/Python39/Tools/scripts/pydoc3.py. you might need to type the full path, or add it to your Microsoft Windows PATH environment variable. 〔see Windows: Environment Variable Tutorial〕 ) ... Loaded module names is stored in the variable sys.modules. import sys import pprint # pretty print loaded modules pprint.pprint(sys.modules) # sample output # {'__main__': <module '__main__' from 'c:\\Users\\xah\\.emacs.d\\temp\\x20221010_0935_b29.py3'>, # '_abc': <module '_abc' (built-in)>, # '_codecs': <module '_codecs' (built-in)>, # ...
🌐
Real Python
realpython.com › python-import
Python import: Advanced Techniques and Tips – Real Python
August 16, 2024 - This command will install the package to your system. structure will then be found on Python’s import path, meaning you can use it anywhere without having to worry about the script directory, relative imports, or other complications. The -e option stands for editable, which is important because it allows you to change the source code of your package without reinstalling it. Note: This kind of setup file works great when you’re working with projects on your own.
🌐
Python documentation
docs.python.org › 3 › tutorial › modules.html
6. Modules — Python 3.14.4 documentation
Now what happens when the user writes from sound.effects import *? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all.
Top answer
1 of 13
18

IMO the best way todo this is to use the http://furius.ca/snakefood/ package. The author has done all of the required work to get not only directly imported modules but it uses the AST to parse the code for runtime dependencies that a more static analysis would miss.

Worked up a command example to demonstrate:

sfood ./example.py | sfood-cluster > example.deps

That will generate a basic dependency file of each unique module. For even more detail use:

sfood -r -i ./example.py | sfood-cluster > example.deps

To walk a tree and find all imports, you can also do this in code: Please NOTE - The AST chunks of this routine were lifted from the snakefood source which has this copyright: Copyright (C) 2001-2007 Martin Blais. All Rights Reserved.

 import os
 import compiler
 from compiler.ast import Discard, Const
 from compiler.visitor import ASTVisitor

 def pyfiles(startPath):
     r = []
     d = os.path.abspath(startPath)
     if os.path.exists(d) and os.path.isdir(d):
         for root, dirs, files in os.walk(d):
             for f in files:
                 n, ext = os.path.splitext(f)
                 if ext == '.py':
                     r.append([d, f])
     return r

 class ImportVisitor(object):
     def __init__(self):
         self.modules = []
         self.recent = []
     def visitImport(self, node):
         self.accept_imports()
         self.recent.extend((x[0], None, x[1] or x[0], node.lineno, 0)
                            for x in node.names)
     def visitFrom(self, node):
         self.accept_imports()
         modname = node.modname
         if modname == '__future__':
             return # Ignore these.
         for name, as_ in node.names:
             if name == '*':
                 # We really don't know...
                 mod = (modname, None, None, node.lineno, node.level)
             else:
                 mod = (modname, name, as_ or name, node.lineno, node.level)
             self.recent.append(mod)
     def default(self, node):
         pragma = None
         if self.recent:
             if isinstance(node, Discard):
                 children = node.getChildren()
                 if len(children) == 1 and isinstance(children[0], Const):
                     const_node = children[0]
                     pragma = const_node.value
         self.accept_imports(pragma)
     def accept_imports(self, pragma=None):
         self.modules.extend((m, r, l, n, lvl, pragma)
                             for (m, r, l, n, lvl) in self.recent)
         self.recent = []
     def finalize(self):
         self.accept_imports()
         return self.modules

 class ImportWalker(ASTVisitor):
     def __init__(self, visitor):
         ASTVisitor.__init__(self)
         self._visitor = visitor
     def default(self, node, *args):
         self._visitor.default(node)
         ASTVisitor.default(self, node, *args) 

 def parse_python_source(fn):
     contents = open(fn, 'rU').read()
     ast = compiler.parse(contents)
     vis = ImportVisitor() 

     compiler.walk(ast, vis, ImportWalker(vis))
     return vis.finalize()

 for d, f in pyfiles('/Users/bear/temp/foobar'):
     print d, f
     print parse_python_source(os.path.join(d, f)) 

2 of 13
14

I recently needed all the dependencies for a given python script and I took a different approach than the other answers. I only cared about top level module module names (eg, I wanted foo from import foo.bar).

This is the code using the ast module:

import ast


modules = set()

def visit_Import(node):
    for name in node.names:
        modules.add(name.name.split(".")[0])

def visit_ImportFrom(node):
    # if node.module is missing it's a "from . import ..." statement
    # if level > 0 it's a "from .submodule import ..." statement
    if node.module is not None and node.level == 0:
        modules.add(node.module.split(".")[0])

node_iter = ast.NodeVisitor()
node_iter.visit_Import = visit_Import
node_iter.visit_ImportFrom = visit_ImportFrom

Testing with a python file foo.py that contains:

# foo.py
import sys, os
import foo1
from foo2 import bar
from foo3 import bar as che
import foo4 as boo
import foo5.zoo
from foo6 import *
from . import foo7, foo8
from .foo12 import foo13
from foo9 import foo10, foo11

def do():
    import bar1
    from bar2 import foo
    from bar3 import che as baz

I could get all the modules in foo.py by doing something like this:

with open("foo.py") as f:
    node_iter.visit(ast.parse(f.read()))
print(modules)

which would give me this output:

set(['bar1', 'bar3', 'bar2', 'sys', 'foo9', 'foo4', 'foo5', 'foo6', 'os', 'foo1', 'foo2', 'foo3'])
🌐
Oregon State University
blogs.oregonstate.edu › techgooder › 2022 › 02 › 10 › managing-imports-in-a-python-project
Managing imports in a Python project – Tech Gooder
February 10, 2022 - Python did not like this at all, and I wound up with this terrible code. import sys import os import time import tensorflow as tf # This import works fine since it's in the same folder # as training_script.py from ml_c import MlAlgoC # Doing work to crawl up the top-level directory of the project # and append that directory to sys.path so that Python can # find our project files script_dir = os.path.dirname(__file__) mymodule_dir = os.path.join(script_dir, '..', '..') sys.path.append(mymodule_dir) # The preceding code was necessary to make these imports # of local project files work.