在 Python 中使用设置文件的最佳做法是什么?

编程入门 行业动态 更新时间:2024-10-27 05:27:55
问题描述

我有一个带有很多参数的命令行脚本.我现在已经到了一个论点太多的地步,我也想有一些字典形式的论点.

I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too.

所以为了简化事情,我想用设置文件来运行脚本.我真的不知道要使用哪些库来解析文件.这样做的最佳做法是什么?我当然可以自己敲出一些东西,但是如果有一些图书馆可以解决这个问题,我会全力以赴.

So in order to simplify things I would like to run the script with a settings file instead. I don't really know what libraries to use for the parsing of the file. What's the best practice for doing this? I could of course hammer something out myself, but if there is some library for this, I'm all ears.

一些要求":

  • 而不是使用 pickle,我希望它是一个易于阅读和编辑的简单文本文件.
  • 我希望能够在其中添加类似字典的数据,即应该支持某种形式的嵌套.
  • Rather than using pickle I would like it to be a straight forward text file that can easily be read and edited.
  • I want to be able to add dictionary-like data in it, i.e., some form of nesting should be supported.

一个简化的伪示例文件:

A simplified pseudo example file:

truck: color: blue brand: fordcity: new yorkcabriolet: color: black engine: cylinders: 8 placement: mid doors: 2

推荐答案

你可以有一个普通的 Python 模块,比如 config.py,像这样:

You can have a regular Python module, say config.py, like this:

truck = dict( color = 'blue', brand = 'ford',)city = 'new york'cabriolet = dict( color = 'black', engine = dict( cylinders = 8, placement = 'mid', ), doors = 2,)

并像这样使用它:

import configprint(config.truck['color'])
  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

在 Python 中使用设置文件的最佳做法是什么?

本文发布于:2023-05-22 18:53:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!