我一直在用香草
def main():
# Do stuff
if __name__ == '__main__':
main()但最近看到人们在做
from absl import app
def main(_):
# Do things
if __name__ == '__main__':
app.run(main)Abseil提供了flags.FLAGS,但是我一直在使用ArgumentParser,它工作得很好,所以在这方面没有取得任何胜利。
那么,为什么要费心走禁欲路线呢?
PS: Reddit上的相关讨论(没有真正回答这个问题):https://www.reddit.com/r/Python/comments/euhl81/is_using_googles_abseil_library_worth_the/
发布于 2022-10-28 17:32:11
考虑一种设计模式,您在cmd行传递一个json文件(其中包含特定于站点的常量)作为Python脚本的输入。比方说,json文件包含不变的常量,您希望以这种方式维护它。
您希望json文件内容中的常量可供项目中的所有模块使用。
其中一种方法是实现一个中心模块,该模块将json反序列化为Python对象。ABSL通过(通过FLAGS)访问中央模块中的输入文件,然后将其存储到一个类变量中,从而帮助您解决这个问题,以便您的项目中的所有模块都可以使用该文件。
如果没有ABSL,首先需要在主模块中解析输入文件,然后将其发送到中央模块。
这方面的代码示例可以是:main.py
from centralmod import DeserializeClass
import centralmod
from absl import flags
from absl import app
_JSON_FILE = flags.DEFINE_string("json_file", None, "Constants", short_name='j', required=True)
def scenario():
import someothermodule
someothermodule.do_something()
def populate_globalvar():
centralmod.populate_somevar()
deserialized_data = DeserializeClass.somevar
def main(argv):
populate_globalvar()
scenario()
if __name__ == '__main__':
app.run(main)centralmod.py
from absl import flags
import json
FLAGS = flags.FLAGS
class DeserializeClass:
@classmethod
def get_value(cls, key):
return DeserializeClass.somevar[key]
def populate_somevar():
with open(FLAGS.json_file) as json_constants_fh:
deserialized_data = json.load(json_constants_fh)
setattr(DeserializeClass, 'somevar', deserialized_data)和someothermod.py
from centralmod import DeserializeClass
site_specific_consts = DeserializeClass.somevar
def do_something():
print(f"\nScenario: Testing. The site-specific constants are:\n{site_specific_consts}")
print(f"the value of key ssh_key_file is {DeserializeClass.get_value('ssh_key_file')}")
print(f"the value of key nodes is {DeserializeClass.get_value('nodes')}")https://stackoverflow.com/questions/63184690
复制相似问题