V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
linkbg
V2EX  ›  Python

Python 配置项的如何全局应用

  •  
  •   linkbg · 2019-07-10 10:21:37 +08:00 · 2440 次点击
    这是一个创建于 1723 天前的主题,其中的信息可能已经有所发展或是发生改变。

    编写一个类或者方法,来读取配置文件,比如项目名称、版本、一些其他方法或类需要用的值。那么这些配置项如何在其他方法(文件)中使用?

    9 条回复    2019-07-16 19:40:57 +08:00
    leishi1313
        1
    leishi1313  
       2019-07-10 10:34:47 +08:00 via Android
    存 json 或者 yml 然后读一下就好了。话说你这像面试人家给你留的作业
    renmu
        2
    renmu  
       2019-07-10 14:40:20 +08:00 via Android
    lolizeppelin
        3
    lolizeppelin  
       2019-07-10 14:40:28 +08:00
    看 openstack 怎么做的~~~
    ssewhy
        4
    ssewhy  
       2019-07-10 15:36:41 +08:00
    介不是君哥吗,许久不见,O(∩_∩)O 哈哈~
    linkbg
        5
    linkbg  
    OP
       2019-07-10 22:43:56 +08:00
    @ssewhy 哈哈哈,感觉我应该换个号了。
    ssewhy
        6
    ssewhy  
       2019-07-11 11:07:42 +08:00
    有时间去你那玩玩......(*^▽^*)
    linkbg
        7
    linkbg  
    OP
       2019-07-11 15:03:43 +08:00
    @ssewhy 欢迎欢迎
    anonymous256
        8
    anonymous256  
       2019-07-11 17:10:15 +08:00
    看完这两篇你就应就知道了。
    https://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-settings-file-in-python
    https://martin-thoma.com/configuration-files-in-python/

    我的看法:

    1. yaml 不是一个好主意, 因为需要给项目引入额外的依赖。首先排除它。
    2. 如果你只是需要配置一些全局的符号常量(symbolic constants), 参考 Django 的做法,使用 setting.py
    参见: https://github.com/deis/example-python-django/blob/master/helloworld/settings.py
    关于使用符号常量: https://constantly.readthedocs.io/en/latest/
    3. 如果你只需要简单的一些键值对(key-value pairs), 可以使用 INI 文件,配置标准库的 configparser 进行解析。
    4. 如果你需要更复杂的配置, 不妨使用 json.

    2,3,4 我都用过。简单的一些,直接用了 settings.py 。有的项目配置文件超过 7000 行了, 用的 json。
    telnetning
        9
    telnetning  
       2019-07-16 19:40:57 +08:00
    是的,可以看看 OpenStack 的做法,具体就是 oslo.config 库。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5195 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 01:19 · PVG 09:19 · LAX 18:19 · JFK 21:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.