在一个非常简短的python脚本中,我们可以编写:
print( help('modules'))
这列出了很多东西,包括以下内容:
PIL _weakrefset html secrets
__future__ _winapi http select
_abc _xxsubinterpreters idlelib selectors
_ast abc imaplib setuptools
请注意,其中包含一些非标准库。例如,我安装了PIL
用于图像处理。我的问题是,print( help('modules'))
中是否有任何标准库缺失?基本上,我想将所有python标准库的名称列表打印到文件中。我的尝试如下所示:
import os
import pathlib as pl
import string
from contextlib import redirect_stdout
class FileFilter:
def __init__(self, filepath):
filepath = pl.Path(str(filepath))
if os.path.exists(filepath):
os.remove(filepath)
# open in `append` mode
self._file = open(filepath, "a")
self.prev_was_comma = False
def write(self, stuff):
lamby = lambda ch:\
"," if ch in string.whitespace else ch
mahp = map(lamby, str(stuff))
for ch in mahp:
if ch != "," or not self.prev_was_comma:
self._file.write(ch)
if ch == ",":
self.prev_was_comma = True
else:
self.prev_was_comma = False
def __del__(self):
self._file.close()
with redirect_stdout(FileFilter("stdlibs.txt")):
help('modules')
# TODO:
# remove opening line
# ,Please,wait,a,moment,while,I,gather,a,list,of,all,available,modules...,
# remove closing line
# ,Enter,any,module,name,to,get,more,help.,Or,type,"modules,spam"
# to,search,for,modules,whose,name,or,summary,contain,the,string,"spam".,
答案 0 :(得分:1)
在 Python 3.10 中,您可以使用 sys.stdlib_module_names。
如果需要,您也可以查看 sys.builtin_module_names。