简体   繁体   English

python从文件中读取数据并计算结果

[英]python read data from file and calculate result

i want to store some values in a python file like blew here is my abc.py file 我想将一些值存储在像blew这样的python文件中,这是我的abc.py文件

{
  21:"This field is required",
  22:"Value can't be null",
  23:"other custom message",
}

then i want to calculate code from a given string in a python function. 那么我想从python函数中的给定字符串计算代码。 example: 例:

def calculate_code(error_message):
    #process error_message and read data from abc.py file
    #calculate error_code
    return eror_code

like if i have error_message = "Value can't be null" then i ll get error_code = 22. 就像如果我有error_message =“值不能为空”,那么我将得到error_code = 22。

what is the best way to do it? 最好的方法是什么?

A sensible solution would be to define a cache class (based on a dictionary) from messages to error codes. 明智的解决方案是定义一个从消息到错误代码的缓存类(基于字典)。 This is not a complete solution, but this provides a skeleton: 这不是一个完整的解决方案,但是提供了一个框架:

from datetime import datetime from os import stat import time 从datetime导入datetime从os import stat导入时间

class Cache(object):
    def __init__(self, filename):
        self._filename = filename
        self._populate_cache()

    def __getitem__(self, name):
        if self._check_file_updated():
           self._populate_cache()
        return self._cache[name]

    def _populate_cache(self):
        self._populate_time = time.mktime(datetime.now().timetuple())
        self._cache = read_file_as_dict(self._filename)
        print "debug: updated cache"

    def _check_file_updated(self):
        return stat(self._filename).st_mtime > self._populate_time


def read_file_as_dict(filename):
    # needs an implementation: just simulating
    return { "Blown up": 25, "Warning": 31 }

Usage: 用法:

cache = Cache("test")
>>> cache["Blown up"]
25
>>> cache["Blown up"]
25

Now I touch the "test" file: 现在,我触摸“测试”文件:

>>> cache["Blown up"]
debug: updated cache
25

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM