2016-06-04 3 views
3

작은 파이썬 학습 응용 프로그램을 개발 중입니다. 학생이 단순히 list, date과 같은 키워드를 검색하는 경우 내 앱은 키워드에 대한 도움말 텍스트로 결과를 제공합니다.Python의 모든 함수, 클래스, 데이터 유형 얻기

먼저 파이썬 내장 코드를 모두 추출하고, 클래스는 help()를 사용하여 json 파일에 텍스트를 추가합니다. 나는 시도 :

>>> import sys 
>>> sys.modules.keys() 
['__future__', 'copy_reg', 'sre_compile', '_hashlib', '_sre', 'encodings', 'site', '__builtin__', 'datetime', '__main__', 'encodings.encodings', 'hashlib', 'abc', 'posixpath', '_random', '_weakrefset', 'errno', 'binascii', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', '_warnings', 'math', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'codecs', 'readline', 'os.path', '_locale', 'sitecustomize', 'signal', 'random', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref'] 

을 위의 결과 내가

>>> bi = sys.modules.get('__builtin__') 
>>> help(bi.list.append) (or) 
>>> bi.list.append.__doc__ 
'L.append(object) -- append object to end' # goes to json file 

sys.modulesre, random 등을 제공 추출 할 수 있습니다. 그러나 위의 모듈 목록에서 datetime을 찾지 못했습니다. 파이썬에서 사용 가능한 모든 함수, 데이터 형식, 클래스 등을 찾는 방법?

참고 : 필자의 목표는 가능한 한 많이 파이썬에서 도움말 텍스트를 추출하는 것입니다. sys.modules뿐만 아니라 모든 방법을 높이 평가할 수 있습니다.

편집 : 처음에는 datetime이 없습니다. 날짜를 가져온 후

>>> import sys 
>>> sys.modules.keys() 
['copy_reg', 'encodings', 'site', '__builtin__', '__main__', 'encodings.encodings', 'abc', 'posixpath', '_weakrefset', 'errno', 'encodings.codecs', '_abcoll', 'types', '_codecs', '_warnings', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'codecs', 'readline', 'os.path', 'sitecustomize', 'signal', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'os', '_weakref'] 

>>> import datetime 
>>> sys.modules.keys() 
['copy_reg', 'encodings', 'site', '__builtin__', 'datetime', '__main__', 'encodings.encodings', 'abc', 'posixpath', '_weakrefset', 'errno', 'encodings.codecs', '_abcoll', 'types', '_codecs', '_warnings', 'genericpath', 'stat', 'zipimport', 'encodings.__builtin__', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'codecs', 'readline', 'os.path', 'sitecustomize', 'signal', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'os', '_weakref'] 
>>> 
+2

결과에서'datetime'을 볼 수 있습니다. 9 번째 색인. – Kasramvd

+0

그 실수에 대해 사과드립니다. 내가 언급 한 것처럼 sys.modules만큼 충분합니까? – ravigadila

+1

''datetime 'in sys.modules == False' 내 컴퓨터에서. – Brian

답변

3

datetime는 표준 라이브러리의 일부입니다 sys.modules에; 해당 datetime.datetime 유형은 목록과 같이 기본 제공되지 않으며 built-in type입니다.

여전히 sys.modules보다는 looking it up, 종종 equally interactively을 반복 주장하는 경우 importing all standard libraries에 의존해야 할 수도 있습니다 : 수입 SYS

from stdlib_list import stdlib_list 

for lib in stdlib_list("2.7"): 
    try: 
     __import__(lib) 
    except ImportError: 
     continue 

assert 'datetime' in sys.modules 

print sys.modules.get('datetime').datetime.__doc__ 
# datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) 
# 
# The year, month and day arguments are required. tzinfo may be None, or an 
# instance of a tzinfo subclass. The remaining arguments may be ints or longs. 
0

당신은 것 help()의 자신의 버전을 만들 싶은 될, 하나의 의미에서 당신은 더 학생 친화적 인 것으로 간주됩니다. 그렇다면 원본으로 이동하여 시작할 수 있습니다. pydoc.py (예 : C:/Python34/lib/pydoc.py과 같은 곳)의 출처를 볼 수 있습니다. 여기에서 help()이 정의되어 있습니다. 예를 들어, 도움말 방법에 대한 실제 코드가 시작됩니다 :

def help(self, request): 
     if type(request) is type(''): 
      request = request.strip() 
      if request == 'help': self.intro() 
      elif request == 'keywords': self.listkeywords() 
      elif request == 'symbols': self.listsymbols() 
      elif request == 'topics': self.listtopics() 
      elif request == 'modules': self.listmodules() 

등 당신은 listkeywords(self)의 코드로 탐구 시작할 수 있습니다

,

당신이 이해하면 (몇 가지 더 elif 절 다음에) 어떻게 help()이 주제를 찾은 다음 사용할 지 결정할 수 있습니다.

그런데 위의 코드 스 니펫은 쉘에 help('keywords') 등을 입력하는 것만으로도 질문에 대한 답변을 얻을 수 있음을 나타냅니다.