我在做一個非常簡單的腳本,它採用下列參數:如果沒有位置參數,打印幫助?
-p --port integer, optional, default 5050
-f --fork boolean, optional, default False
action string, required, needs to be either start or stop
我試過在argparse實現這一點,但是當沒有提供操作字符串它不打印的幫助,它只是失敗的所有醜陋如:
usage: __init__.py [-h] [-p PORT] [-f] {start,stop}
__init__.py: error: argument action: invalid choice: '__init__.py' (choose from 'start', 'stop')
即使當我通過「開始」或「停止」,它會失敗,並有相同的消息。這裏是我的代碼:
parser = argparse.ArgumentParser(description="Start or stop the server.",
epilog="If you don't know what you're doing, run. Run for your life.\n")
parser.add_argument("-p", "--port", type=int, nargs=1, default=5050,
dest="port", help="The port to run the server on.")
parser.add_argument("-f", "--fork", action="store_true", default=False,
dest="fork", help="Fork to background? Default is false.")
parser.add_argument("action", type=str, choices=("start","stop"), help="Whether to 'start' or 'stop' the server.")
我在做什麼錯在這裏?希望我的意圖從我的代碼中很清楚。
你是怎麼調用'__init __。py'?不知怎的,'__init.py__'作爲第一個參數提供,就好像你在調用'python __init__.py __init __。py'。 – unutbu 2012-01-16 23:37:45
你是怎麼調用'parser.parse_args()'?如果我說'parser.parse_args(['start'])',我得到一個'Namespace'對象。 – chepner 2012-01-16 23:38:35