ArgumentParser -h(帮助)无法使用

0 投票
3 回答
790 浏览
提问于 2025-04-17 12:41

我无法让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

好的,这个答案有点奇怪。问题是通过以下方式解决的:

python myscript.py -h

如果你把python添加到你的路径中,设置文件关联,然后只需要这样做:

myscript.py -h 

它就不会识别-h这个参数了。

1

如果你从命令行运行这个脚本,它会只打印出'goodbye'。你需要把argparse的代码放在if __name__ == "__main__":之后。

2

这个argsparse的代码其实并没有被执行。当你从命令行运行这个脚本时,你实际上是在调用main()这个函数,它只是打印一些东西然后退出。要让这个功能正常工作,你需要在main()函数里调用parse_args()

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上运行得很好——我对此感到很奇怪。

撰写回答