日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python做项目管理_python项目实现配置统一管理的方法

發布時間:2024/1/1 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python做项目管理_python项目实现配置统一管理的方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一個比較大的項目總是會涉及到很多的參數,最好的方法就是在一個地方統一管理這些參數。最近看了不少的python項目,總結了兩種很有意思的配置管理方法。

第一種 基于easydict實現的配置管理

首先需要安裝numpy、easydict以及yaml:

pip install numpy

pip install easydict

pip install yaml

就可以了。

然后定義配置類config.py:

import numpy as np

from easydict import EasyDict as edict

import yaml

# 創建dict

__C = edict()

cfg = __C

# 定義配置dict

__C.dev = edict()

__C.dev.name = 'dev-xingoo'

__C.dev.age = 20

__C.test = edict()

__C.test.name = 'test-xingoo'

__C.test.age = 30

# 內部方法,實現yaml配置文件到dict的合并

def _merge_a_into_b(a, b):

"""Merge config dictionary a into config dictionary b, clobbering the

options in b whenever they are also specified in a.

"""

if type(a) is not edict:

return

for k, v in a.items():

# a must specify keys that are in b

if k not in b:

raise KeyError('{} is not a valid config key'.format(k))

# the types must match, too

old_type = type(b[k])

if old_type is not type(v):

if isinstance(b[k], np.ndarray):

v = np.array(v, dtype=b[k].dtype)

else:

raise ValueError(('Type mismatch ({} vs. {}) '

'for config key: {}').format(type(b[k]),

type(v), k))

# recursively merge dicts

if type(v) is edict:

try:

_merge_a_into_b(a[k], b[k])

except:

print(('Error under config key: {}'.format(k)))

raise

else:

b[k] = v

# 自動加載yaml文件

def cfg_from_file(filename):

"""Load a config file and merge it into the default options."""

with open(filename, 'r', encoding='utf-8') as f:

yaml_cfg = edict(yaml.load(f))

_merge_a_into_b(yaml_cfg, __C)

使用的時候很簡單,main.py:

from config import cfg_from_file

from config import cfg

cfg_from_file('config.yml')

print(cfg.dev.name)

print(cfg.test.name)

同級目錄下創建配置文件config.yaml

dev:

name: xingoo-from-yml

輸出:

xingoo-from-yml

test-xingoo

總結

這樣的好處就是在任何的Python文件中只要from config import cfg就可以使用配置文件。

第二種 基于Class實現

這種基于普通的python對象實現的,創建config2.py:

class Config:

def __init__(self):

self.name = 'xingoo-config2'

self.age = 100

使用的時候直接創建一個新的對象,如何python模塊之間需要引用這個變量,那么需要把配置對象傳過去:

import config2 as config2

cfg2 = config2.Config()

print(cfg2.name)

print(cfg2.age)

輸出為:

xingoo-config2

100

總結

第二種方法簡單粗暴...不過每次傳遞參數也是很蛋疼。還是喜歡第一種方式。

總結

以上是生活随笔為你收集整理的python做项目管理_python项目实现配置统一管理的方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。