programing

Import된 모듈을 나열하는 방법

yoursource 2022. 11. 1. 22:51
반응형

Import된 모듈을 나열하는 방법

가져온 모듈을 모두 열거하려면 어떻게 해야 합니까?

예: 다음 정보를 얻으려고 합니다.['os', 'sys']다음 코드부터:

import os
import sys
import sys
sys.modules.keys()

현재 모듈에 대해서만 모든 Import를 취득하는 대략적인 방법은 모듈 검사입니다.

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

로컬 Import 또는 다음과 같은 비모듈 Import는 반환되지 않습니다.from x import y. 이것은 반환되는 것에 주의해 주세요.val.__name__원래 모듈 이름을 얻을 수 있습니다.import module as alias; 에일리어스를 원할 경우 대신 이름을 지정합니다.

의 교차점을 찾다sys.modules와 함께globals:

import sys
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]

스크립트 외부에서 이 작업을 수행할 경우:

파이썬 2

from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script("myscript.py")
for name, mod in finder.modules.iteritems():
    print name

파이썬 3

from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script("myscript.py")
for name, mod in finder.modules.items():
    print(name)

그러면 myscript.py에서 로드한 모든 모듈이 인쇄됩니다.

예를 들어, 수학을 Import했다고 가정하면 다음과 같습니다.

>>import math,re

이제 같은 용도를 보자면

>>print(dir())

Import 전과 Import 후에 실행하면 차이를 알 수 있습니다.

print [key for key in locals().keys()
       if isinstance(locals()[key], type(sys)) and not key.startswith('__')]

실제로 다음과 같은 환경에서 매우 잘 작동합니다.

import sys
mods = [m.__name__ for m in sys.modules.values() if m]

Import 가능한 모듈 이름을 가진 목록이 생성됩니다.

이 코드는 모듈에 의해 Import된 모듈을 나열합니다.

import sys
before = [str(m) for m in sys.modules]
import my_module
after = [str(m) for m in sys.modules]
print [m for m in after if not m in before]

이 기능은 코드를 실행하기 위해 새로운 시스템에 설치하는 외부 모듈을 알고 싶을 때 유용합니다.몇 번이고 다시 시도할 필요가 없습니다.

이 리스트는 표시되지 않습니다.sys하나 이상의 모듈을 Import합니다.

여기에는 왜곡된 답변이 많이 있습니다.그 중 일부는 최신 Python에서 예상대로 작동하지 않습니다.3.10스크립트의 완전 Import 모듈을 입수하기 위한 최적의 솔루션(내부 모듈 취득에는 적합하지 않음) __builtins__다음 명령을 사용합니다.

# import os, sys, time, rlcompleter, readline
from types import ModuleType as MT
all = [k for k,v in globals().items() if type(v) is MT and not k.startswith('__')]
", ".join(all)

# 'os, sys, time, rlcompleter, readline'

위의 결과는 @marcin의 답변에서 영감을 얻은 것입니다.이 답변은 기본적으로 모든 모듈과 글로벌을 통합한 것입니다.

# import os, sys, time, rlcompleter, readline
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]
for i in allmodules: print (' {}\n'.format(i))

#<module 'time' (built-in)>
#<module 'os' from 'C:\\Python310\\lib\\os.py'>
#<module 'sys' (built-in)>
#<module 'readline' from 'C:\\Python310\\lib\\site-packages\\readline.py'>
#<module 'rlcompleter' from 'C:\\Python310\\lib\\rlcompleter.py'>

또한 첫 번째 솔루션에는 수입 순서가 반영되지만 마지막 솔루션에는 반영되지 않습니다.단, 모듈 패스는 디버깅에 도움이 될 수 있는두 번째 솔루션에서도 제공됩니다.

추신. 제가 정확한 어휘를 사용하고 있는지 잘 모르기 때문에 정정할 필요가 있으면 코멘트를 주세요.

@Lila에서 훔침(포맷이 없기 때문에 코멘트를 할 수 없음)에는 모듈의 /path/도 표시됩니다.

#!/usr/bin/env python
import sys
from modulefinder import ModuleFinder
finder = ModuleFinder()
# Pass the name of the python file of interest
finder.run_script(sys.argv[1])
# This is what's different from @Lila's script
finder.report()

그 결과, 다음과 같이 됩니다.

Name                      File
----                      ----

...
m token                     /opt/rh/rh-python35/root/usr/lib64/python3.5/token.py
m tokenize                  /opt/rh/rh-python35/root/usr/lib64/python3.5/tokenize.py
m traceback                 /opt/rh/rh-python35/root/usr/lib64/python3.5/traceback.py
...

그리핑이나 뭐 그런 거에 적합하다.주의하세요, 길어요!

이 경우 목록 이해를 사용하는 것이 좋습니다.

>>> [w for w in dir() if w == 'datetime' or w == 'sqlite3']
['datetime', 'sqlite3']

# To count modules of interest...
>>> count = [w for w in dir() if w == 'datetime' or w == 'sqlite3']
>>> len(count)
2

# To count all installed modules...
>>> count = dir()
>>> len(count)

언급URL : https://stackoverflow.com/questions/4858100/how-to-list-imported-modules

반응형