python 3中所有导入的列表

时间:2011-04-12 09:21:03

标签: python import python-3.x

如何通过程序查找python 3中所有可用导入的列表?我一开始尝试了这个,但无法理解它返回的内容

import sys
    sys.modules

我认为这不是方法,尽管这首先是我的想法。我在网上搜索了http://effbot.org/librarybook/core-modules-index.htm

有人可以告诉我这是否正确吗?

6 个答案:

答案 0 :(得分:2)

来自http://docs.python.org/library/sys.html(在python stdlib上寻找文档的好地方)

  

<强> sys.builtin_module_names

     

是一个字符串给出的元组(有点像不可变的匿名结构)   编译到此Python中的所有模块的名称   解释

     

<强> sys.modules中

     

这是一个将模块名称映射到模块(模块对象)的字典   哪些已经加载。这可以被操纵强制   重装模块和其他技巧。请注意删除模块   来自这个字典与调用reload()不一样   相应的模块对象。

所以模块是一个字典(模块名称到实际模块对象的映射)。要获得名称类型sys.modules.keys(),尽管它可能没那么有用。

答案 1 :(得分:1)

你为什么要那样做?

无论如何,我怀疑你的链接与你的要求有关。 python附带的可用模块列表如下:

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

内置的模块列表如下:

sys.builtin_module_names

要获取可以导入的所有内容的列表,包括已安装的模块,您必须通过sys.path并“手动”查找模块,这不是一个完全无关紧要的任务,考虑到这些都可以是python文件,编译文件,如.so和.dll,目录甚至zip文件,你也必须处理pth文件。

但是,我认为没有必要这样做。

答案 2 :(得分:1)

这是my answer for recent Python 2.x。它当然不是完美的,我甚至没有在Python 3上测试它,但我认为它有一个合理的机会比目前在这里的任何其他答案和评论更有用 - 当然它对我的特定用途来说已经足够好了案件。由于LennartRegebro是移植到Python 3的专家,我相信他可以更好地了解这种方法。

答案 3 :(得分:1)

您可能只需要从模块导入的内容列表。在导入模块后,例如&#34; foo.py&#34;,您可以在python解释器中键入以下内容,以获取模块&#34; foo&#34;中可用名称的排序列表。

dir(foo)

导入dir(sys)后尝试sys

您还可以在提示符下键入dir(),以获取解释器当前正在使用的已排序名称列表。名称代表变量,函数,模块,类等。

有关python模块的更全面信息,您可以在official documentation内进行搜索。特别在教程部分中查看。

这里是python 3中模块的官方信息:http://docs.python.org/py3k/tutorial/modules.html

答案 4 :(得分:0)

与Python 2和Python 3一样 (使用下一版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))

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

测试环境

$ 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

答案 5 :(得分:0)

我使用的 python 实现无法访问 import pkgutil

我还想说明两者之间的区别:

  • 系统/内置模块
  • 使用 pip 安装的模块
  • 通过修改 PYTHONPATH 创建的模块(例如本地项目导入)

这个解决方案并不完美,它需要安装 regex 模块,但它非常接近。

# 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