List of all imports in python 3
Asked Answered
F

6

5

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 this struck my mind first. I searched the web and found this http://effbot.org/librarybook/core-modules-index.htm

Can someone tell me whether this is correct or not?

Finnish answered 12/4, 2011 at 9:21 Comment(7)
so this would be a list of all module names that one can import?Expander
Always explain what you are doing, why you are doing it and in what way it isn't working. You are most likely asking the wrong question.Fantasist
Apologies for that. Probably yes. I guess I am looking for something like finding out imports that python has. Like import sys import string etc.Finnish
I'm not sure there's anything particularly specific to Python 3 about your question.Calciferol
Related: How can I get a list of all the Python standard library modules?Deirdre
Does this answer your question? How to get a list of all the Python standard library modules?Winged
@Winged Not a dupe, because "available imports" >= "stdlib imports" (i.e. including 3rd party packages available)Deirdre
E
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.

Enthalpy answered 12/4, 2011 at 9:52 Comment(2)
Yeah, sys.modules.keys() revealed it. I was able to see os, os.path etc which I use. I just wanted to know (out of curiosity)Finnish
No, sys.modules.keys() does not show available imports, but what you have imported. Completely different question.Fantasist
H
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
Hellas answered 5/2, 2017 at 9:19 Comment(0)
A
2

it's possible that you merely needed a list of things imported from a module. after importing a module, say "foo.py", you can type the following within python interpreter to get a sorted list of names available in module "foo".

dir(foo)

try dir(sys) after importing sys.

you can also type dir() at the prompt to get a sorted list of names currently in use by the interpreter. the names represent variables, functions, modules, classes, etc.

for more thorough information on python modules you can search within the official documentation. specially look within the tutorial section.

here is official info on modules in python 3: http://docs.python.org/py3k/tutorial/modules.html

Assume answered 24/6, 2012 at 14:23 Comment(0)
C
1

Here's my answer for recent Python 2.x. It's certainly not perfect, and I haven't even tested it on Python 3, but I think it has a reasonable chance of being much more useful than any of the other answers and comments currently here - certainly it was good enough for my particular use case. As LennartRegebro is the expert in porting to Python 3, I'm sure he can shed more light on this approach.

Calciferol answered 25/1, 2012 at 22:16 Comment(0)
F
0

Why would you want to do that?

In any case, I doubt your link is relevant for what you are asking. The list of available modules that ships with python is here:

http://docs.python.org/py3k/library/index.html

The list of modules that are built in is here:

sys.builtin_module_names

To get a list of everything you can import, including installed modules, you would have to go through the sys.path and look for modules "manually", which is not an entirely trivial task, considering these can be both python files, compiled files like .so and .dll, directories and even zip files, and you would have to handle pth files too.

However, I don't see any need for ever doing that.

Fantasist answered 12/4, 2011 at 10:12 Comment(6)
Thanks, just out of curiosity.Finnish
There are several good reasons for needing to obtain this list programmatically, for example in order to exclude lines relating to standard libraries from a stack trace, or to detect all non-standard-library imports within a Python codebase.Calciferol
@LennartRegebro: sorry, I don't understand your comment at all. In case it wasn't clear, I was replying to your previous comment "However, I don't see any need for ever doing that".Calciferol
@AdamSpiers: Read the answer more carefully. "To get a list of everything you can import" is not equivalent to sys.builtin_module_names which is what you need in your examples.Fantasist
@LennartRegebro: Why do you think my examples only need sys.builtin_module_names ? The first sentence of the link for the first example says "I want something like sys.builtin_module_names except for the standard library" - I don't know how the poster could have made it any clearer that builtin_modules_names was insufficient for his use case. And the second example was my own use case which caused me to comment on this question in the first place, and it also very definitely needs a list of everything the Python standard library can offer. Perhaps it is you that needs to read again.Calciferol
@AdamSpiers: Right, sorry, it's not sys.builtin_modules_names you need, but the list of modules that ships with python. My bad. Still, " I don't see any need for ever doing that" refers to getting a list of everything that is installed. which is a different thing.Fantasist
J
-1

The implementation of python I was using didn't have access to import pkgutil

I also wanted to tell the difference between:

  • system / builtin modules
  • modules installed with pip
  • modules created by modifying the PYTHONPATH (e.g. local project imports)

This solution isn't perfect, it requires installing the regex module, however it is pretty close.

# returns a set of strings
def list_module_names(system_only=False, installed_only=False):
    # check if a file/folder is a package name (and return the package name if true)
    def item_is_python_module(item_name, parent_path):
        import regex
        import os
        
        if os.path.isdir(os.path.join(parent_path, item_name)):
            # simple name of folder
            result = regex.match(r"([a-zA-Z][a-zA-Z_0-9]*)$", item_name)
            if result:
                return result[1]
            
            # dist name
            result = regex.match(r"([a-zA-Z][a-zA-Z_0-9]*)-\d+(\.\d+)*\.dist-info$", item_name)
            if result:
                return result[1]
        # if file
        else:
            # regular python file
            result = regex.match(r"([a-zA-Z_][a-zA-Z_0-9\-]*)\.py$", item_name)
            if result:
                return result[1]
            
            # cpython file
            result = regex.match(r"([a-zA-Z_][a-zA-Z_0-9\-]*)\.cpython-.+\.(so|dll)$", item_name)
            if result:
                return result[1]
            
            # nspkg.pth file
            result = regex.match(r"([a-zA-Z_][a-zA-Z_0-9\.\-]*)-\d+(\.\d+)*-.+-nspkg.pth$", item_name)
            if result:
                return result[1]
            
            # egg-link file
            result = regex.match(r"([a-zA-Z_][a-zA-Z_0-9\.\-]*)\.egg-link$", item_name)
            if result:
                return result[1]
            
            
        return False
    
    import os
    import sys
    import subprocess
    
    # 
    # what paths to look at
    # 
    paths = sys.path
    if system_only:
        paths = eval(subprocess.run([sys.executable, '-S', '-s', '-u', '-c', 'import sys;print(list(sys.path))'], capture_output=True, env={"PYTHONPATH": "","PYTHONHOME": "",}).stdout)
    else:
        paths = eval(subprocess.run([sys.executable, '-u', '-c', 'import sys;print(list(sys.path))'], capture_output=True, env={"PYTHONPATH": "","PYTHONHOME": "",}).stdout)
    # 
    # add all names
    # 
    all_modules = set()
    for each_path in paths:
        if os.path.isdir(each_path):
            files = os.listdir(each_path)
            local_modules = [ item_is_python_module(each_file_name, each_path) for each_file_name in files ]
            # filter out invalid ones
            local_modules = set([ each for each in local_modules if each is not False ])
            all_modules |= local_modules
    # special module
    all_modules.add('__main__')
    return all_modules

Jewelry answered 29/7, 2021 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.