ArgumentParser -h(帮助)不起作用

时间:2012-02-09 14:46:23

标签: python command-line-arguments

我无法让ArgumentParser工作。以下是什么问题:

import argparse
parser=argparse.ArgumentParser(description='''I wish this description would output''',
                                            epilog='''Please out the epilog''')

parser.add_argument('-l', type=str, default='info', help='logging level. Default is info. Use debug if you have problems.')
args=parser.parse_args()

def main():
    print("goodbye")

if __name__ == "__main__":
    #main
    main()

当我跑myscript -h时,我看不到任何帮助。

我在Windows 7上运行Python 2.7。我的路径上有Python,pathext也设置为:

PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.py

3 个答案:

答案 0 :(得分:2)

argsparse代码实际上从未被执行过。通过从命令行执行脚本,您将调用main(),它只是打印和退出。您必须在parse_args()函数中调用main()才能生效。

import argparse

# Personally, I think these belong in the main()
# function as well, but they don't need to be.
parser = argparse.ArgumentParser(
    description="I wish this description would output",
    epilog="Please out the epilog"
)
parser.add_argument(
    "-l",
    type=str,
    default="info",
    help="logging level. Default is info. Use debug if you have problems."
)

def main():
    args = parser.parse_args() # Parses arguments
    print("goodbye")

if __name__ == "__main__":
    main() # Calls main

产地:

~/Desktop $ python untitled.py --help
usage: untitled.py [-h] [-l L]

I wish this description would output

optional arguments:
  -h, --help  show this help message and exit
  -l L        logging level. Default is info. Use debug if you have problems.

Please out the epilog

jcollado声称你的代码在Ubuntu上工作得很好 - 我发现这非常好奇。

答案 1 :(得分:1)

如果您从命令行运行此脚本,则只需打印“再见”,请将argparse代码放在if __name__ == "__main__":之后。

答案 2 :(得分:0)

好的奇怪答案。通过将程序调用为:

解决了该问题
python myscript.py -h

如果将python添加到路径中,请设置文件关联,然后执行:

myscript.py -h 

它不会拿起-h

相关问题