简体   繁体   English

带有动作='store_true'的Argparse无法正常工作

[英]Argparse with action='store_true' not working as expected

The idea is to add a flag ( --slack , or -s ) when running the script, so that I don't have to comment out the rep.post_report_to_slack() method every time I don't want to use it. 这个想法是在运行脚本时添加一个标志( --slack-s ),这样我就不必在每次不想使用rep.post_report_to_slack()方法时都将其注释掉。 When I run: 当我跑步时:

$ python my_script.py --slack

I get the error: 我得到错误:

my_script.py: error: unrecognized arguments: --slack

Here's the code: 这是代码:

def main():
    gc = Google_Connection()
    meetings = gc.meetings

    rep = Report(meetings)

    if args.slack:
        rep.post_report_to_slack()
        print('posted to slack')


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--slack', help='post to slack', 
        action='store_true')
    args = parser.parse_args()
    main()

Your code works, but it relies on args being available in the module namespace, which isn't great because, for one thing, it means you can't use your function without calling the script from the command line. 您的代码可以工作,但是它依赖于模块名称空间中的args ,这不是很好,因为,一方面,这意味着您必须先从命令行调用脚本,才能使用函数。 A more flexible and conventional approach would be to write the function to accept whatever arguments it needs, and then pass everything you get from argparse to the function: 一种更灵活和常规的方法是编写函数以接受所需的任何参数,然后将您从argparse获得的所有信息传递给函数:

# imports should usually go at the top of the module
import argparse

def get_meeting_report(slack=False):

    gc = Google_Connection()
    meetings = gc.meetings

    rep = Report(meetings)

    if slack:
        rep.post_report_to_slack()
        print('posted to slack')

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--slack', help='post to slack',
        action='store_true')
    args = parser.parse_args()
    args = vars(args)
    get_meeting_report(**args)

Now you can also more easily use your function outside of argparse by calling it directly. 现在,您还可以通过直接调用argparse来更轻松地使用函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM