2016-11-30 3 views
1

"help()"를 사용하여 패키지의 기존 도움말 정보를 볼 수 있음을 알고 있습니다. 하지만 필자가 직접 함수/클래스를 작성한 후에 "도움말"에서 도움말 문서를 볼 수있게하려면 어떻게해야합니까? 나는 "comment"의 첫 번째 줄이 doc 속성이라는 것을 알고 있습니다. 그러나 그것은 제가 원한 것이 아닙니다.파이썬 함수/클래스에 "도움말"정보를 추가하는 방법은 무엇입니까?

내 패키지를 컴파일하고 다른 사용자가 "help()"에서 볼 수 있도록하고 싶습니다. 그렇게하는 방법?

답변

1

help()은 전체적으로 __doc__ 속성 (및 함수 인수의 인트로 스펙 션)을 기반으로하므로 모듈, 클래스 및 함수에 모두 docstring이 있는지 확인하십시오.

문서화 문자열이 하지 주석, 그것은 상단에 노출 된 문자열 리터럴 권리 :

>>> import requests 
>>> requests.__doc__ 
'\nRequests HTTP library\n~~~~~~~~~~~~~~~~~~~~~\n\nRequests is an HTTP library, written in Python, for human beings. Basic GET\nusage:\n\n >>> import requests\n >>> r = requests.get(\'https://www.python.org\')\n >>> r.status_code\n 200\n >>> \'Python is a programming language\' in r.content\n True\n\n... or POST:\n\n >>> payload = dict(key1=\'value1\', key2=\'value2\')\n >>> r = requests.post(\'http://httpbin.org/post\', data=payload)\n >>> print(r.text)\n {\n  ...\n  "form": {\n  "key2": "value2",\n  "key1": "value1"\n  },\n  ...\n }\n\nThe other HTTP methods are supported - see `requests.api`. Full documentation\nis at <http://python-requests.org>.\n\n:copyright: (c) 2016 by Kenneth Reitz.\n:license: Apache 2.0, see LICENSE for more details.\n' 
: 예를 들어

"""This is a module docstring, shown when you use help() on a module""" 

class Foo: 
    """Help for the class Foo""" 

    def bar(self): 
     """Help for the bar method of Foo classes""" 

def spam(f): 
    """Help for the spam function""" 

가 인기 타사 requests 모듈은 문서화 문자열이있다

help()으로 직접 렌더링되고 모듈 내용 (재귀 적으로는 내용 docstrings)과 함께 표현됩니다.

>>> help('requests') 
Help on package requests: 

NAME 
    requests 

DESCRIPTION 
    Requests HTTP library 
    ~~~~~~~~~~~~~~~~~~~~~ 

    Requests is an HTTP library, written in Python, for human beings. Basic GET 
    usage: 

     >>> import requests 
     >>> r = requests.get('https://www.python.org') 
     >>> r.status_code 
     200 
[...] 
1

argparse : https://docs.python.org/2/howto/argparse.html을 사용할 수 있습니다. 이를 통해 사용자 정의 할 수 있고 인수 설명을 추가 할 수있는 --help 매개 변수를 작성할 수 있습니다.

예 :

parser = argparse.ArgumentParser(description = "Write your help documentation here...") 
parser.add_argument('config.txt', nargs='?', help='Write about your positional arguments here') 
args = parser.parse_args() 

사람이 --help으로 프로그램을 실행할 때 그래서 출력 :

$python yourProgram.py --help 
usage: yourProgram.py [-h] [config.txt] 

Write your help documentation here... 

positional arguments: 
config.txt Write about your positional arguments here 

optional arguments: 
-h, --help show this help message and exit