简体   繁体   English

在Python中解析参数的最佳做法是什么?

[英]What is the best practice for parsing arguments in Python?

As I don't have much experience in Python, I'm always trying to follow the Google Python Style Guide . 由于我在Python方面没有太多经验,因此我一直在尝试遵循Google Python样式指南 The guide contains the following sentence. 该指南包含以下句子。

"Even a file meant to be used as a script should be importable and a mere import should not have the side effect of executing the script's main functionality." “即使是打算用作脚本的文件也应该是可导入的,而仅仅导入不应该具有执行脚本主要功能的副作用。”

Therefore, I searched for a way to override __getattr__ , and have been using this ArrtDict class for arguments parsing as follows. 因此,我寻找了一种覆盖__getattr__ ,并一直使用此ArrtDict类进行参数解析,如下所示。

import argparse

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

def parse_args(args):
    if isinstance(args, list):
        parser = argparse.ArgumentParser()
        parser.add_argument('--args1')
        return parser.parse_args(args)
    else:
        return AttrDict(args)

def main(args):
    args = parse_args(args)

if __name__ == '__main__':
    import sys
    main(sys.argv[1:])

What would be the best practice for arguments parsing in Python? 在Python中解析参数的最佳做法是什么?

What the sentence you're referring to is saying is that you should have this line in your script file: 您指的是该句子的意思是您的脚本文件中应包含以下行:

if __name__ == '__main__':

And that any code that runs the script should appear in that block. 并且任何运行脚本的代码都应出现在该块中。 By doing so, you ensure that the code won't automatically run when you import it from another file, since importing ignores the if statement mentioned above. 这样做可以确保从另一个文件导入代码时,该代码不会自动运行,因为导入会忽略上述的if语句。

For processing arguments (which should exist in the if block mentioned above, since you wouldn't want to do that when importing), you should use argparse for everything after Python 2.7. 对于处理参数(应该在上述if块中存在,因为在导入时您不希望这样做),应该对Python 2.7之后的所有内容使用argparse。 Here's a link to the documentation: 这是文档的链接:

Python argparse library Python argparse库

You shouldn't have to override __getattr__ 您不必重写__getattr__

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

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