python配置文件的两种方式


前言

在运行项目程序时通常会有一个配置文件,配置文件是用于配置程序的参数和初始化设置的文件。

比如现在要做一个项目,在部署程序时,需要摄像头IP地址、数据库地址、数据库名称,这些都可以作为配置项写入配置文件。当程序实地部署时,只需要修改配置文件,不需要去代码当中到处查找修改。

本文以下配置内容以配置多个摄像头为例。


py文件作为配置文件

新建一个config.py文件,将程序运行所需的摄像头参数写入一个类中。

# -*- coding: utf-8 -*- 
# @Time : 2022/7/11 16:03 
# @Author : JulyLi
# @File : config.py.py

class Config:
    cam1_ulr = "rtsp://admin:admin111@192.168.1.100:554/main"
    cam2_ulr = "rtsp://admin:admin111@192.168.1.101:554/main"

测试代码:

# -*- coding: utf-8 -*- 
# @Time : 2022/7/11 16:14 
# @Author : JulyLi
# @File : run_cam.py

import cv2
from multiprocessing import Process
import time
from config import Config


def video_show(url):
    capture = cv2.VideoCapture(url)
    while True:
        ref, frame = capture.read()
        if ref is False:
            print("视频读取失败:{}".format(url))
            time.sleep(0.5)
            capture = cv2.VideoCapture(url)  # 重新进行获取
            print("视频重连成功")
            continue
        cv2.namedWindow("demo", 0)
        cv2.imshow("demo", frame)
        cv2.waitKey(1)


def main():
    cam1_ulr = Config.cam1_ulr
    cam2_ulr = Config.cam2_ulr
    p = Process(target=video_show, args=(cam1_ulr,))
    p.start()
    p = Process(target=video_show, args=(cam2_ulr,))
    p.start()


if __name__ == '__main__':
    main()
    


yaml文件作为配置文件

首先需要安装相应的包

pip install pyyaml

yaml支持的数据结构有3种:

  • 对象:键值对的集合,又称映射(mapping)/哈希(hashes)/字典(dictionary)
  • 数组:一组按次序排列的值,又称序列(sequence)/列表(list)
  • 纯量(scalars):单个的,不可再分的值

对象:对象的一组键值,使用冒号表示(注意:编写的时候最好冒号前后各空一个空格)

animal : dog

类似于python中的字典

{animal : "dog"}

数组:一组连词线构成的行,组成一组数组

- animal
- vegetables
- meet
- people

类似于python中的列表

["animal","vegetables","meet","people"]

复合结构:对象和数组可以结合使用,形成复合结构

language:
	- Python
	- Java
	- PHP
websites:
	Python : python.org
	Java : java.com
	YAML : yaml.org

转换为python形式:

{language:["Python","Java","PHP"],websites:{"Python":"python.org","Java":"java.com","YAML":"yaml.org"}}

新建一个config.yaml文件,将程序运行所需的摄像头参数写入一个类中。

cam_config:
  -
    url: rtsp://admin:admin111@192.168.1.100:554/main
  -
    url: rtsp://admin:admin111@192.168.1.101:554/main

测试代码:

# -*- coding: utf-8 -*- 
# @Time : 2022/5/18 17:47 
# @Author : JulyLi
# @File : run_cam.py

import cv2
import yaml
from multiprocessing import Process
import time


def video_show(url):
    capture = cv2.VideoCapture(url)
    while True:
        ref, frame = capture.read()
        if ref is False:
            print("视频读取失败:{}".format(url))
            time.sleep(0.5)
            capture = cv2.VideoCapture(url)  # 重新进行获取
            print("视频重连成功")
            continue
        cv2.namedWindow("demo",0)
        cv2.imshow("demo", frame)
        cv2.waitKey(1)



def main():
    file = open('test.yaml', 'r', encoding="utf-8")
    # datas为load_all()方法返回的迭代器对象
    datas = yaml.load(file, Loader=yaml.FullLoader)
    # for data in datas:
    print(datas)
    cam_data = datas["cam_config"]
    print(cam_data)
    print(len(cam_data))
    for i in range(len(cam_data)):
        url = cam_data[i]["url"]
        p = Process(target=video_show, args=(url,))
        p.start()


if __name__ == '__main__':
    main()

效果展示:
同时起多个摄像头
在这里插入图片描述


总结

目前就先记录下py文件与yaml文件作为配置文件的过程,py文件是最简单的配置方式,但是缺少相应的层级关系;yaml大小写敏感、使用缩进表示层级关系,#表示注释。
它们之间各有优劣,可以根据自己实际的需求和团队协作要求来具体选择。笔者个人建议优先yaml文件作为配置文件的方式。
参考文档:
https://blog.csdn.net/qq_44614026/article/details/120028490
如果阅读本文对你有用,欢迎一键三连呀!!!
2022年7月12日10:11:38
在这里插入图片描述

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
创建Python配置文件两种常见的方式: 1. 使用Python内置的ConfigParser模块来创建配置文件 首先,需要在Python代码中导入ConfigParser模块: ```python import configparser ``` 然后,创建一个ConfigParser对象,并添加配置项: ```python config = configparser.ConfigParser() config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Port'] = '50022' topsecret['ForwardX11'] = 'no' config['DEFAULT']['ForwardX11'] = 'yes' ``` 最后,将配置写入文件: ```python with open('example.ini', 'w') as configfile: config.write(configfile) ``` 这会在当前目录下创建一个名为example.ini的配置文件,内容如下: ``` [DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [bitbucket.org] user = hg [topsecret.server.com] port = 50022 forwardx11 = no ``` 2. 使用JSON格式创建配置文件 首先,创建一个字典来存储配置项: ```python config = { 'DEFAULT': { 'ServerAliveInterval': 45, 'Compression': True, 'CompressionLevel': 9, 'ForwardX11': True }, 'bitbucket.org': { 'User': 'hg' }, 'topsecret.server.com': { 'Port': 50022, 'ForwardX11': False } } ``` 然后,使用Python内置的json模块将字典转换为JSON格式,并写入文件: ```python import json with open('example.json', 'w') as configfile: json.dump(config, configfile) ``` 这会在当前目录下创建一个名为example.json的配置文件,内容如下: ```json { "DEFAULT": { "ServerAliveInterval": 45, "Compression": true, "CompressionLevel": 9, "ForwardX11": true }, "bitbucket.org": { "User": "hg" }, "topsecret.server.com": { "Port": 50022, "ForwardX11": false } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI小笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值