一些小方法【二】

本文为博主原创,未经授权,严禁转载及使用。
本文链接:https://blog.csdn.net/zyooooxie/article/details/127978957

之前写过一篇 介绍自己常用的方法, https://blog.csdn.net/zyooooxie/article/details/104494716 ,再做些分享。

【实际这篇博客推迟发布N个月】

个人博客:https://blog.csdn.net/zyooooxie

【以下所有内容仅为个人项目经历,如有不同,纯属正常】

公共、全局变量

"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
@email: [email protected]
"""

gl_datetime_format = '%Y-%m-%d %H:%M:%S'

gl_date_format = '%Y-%m-%d'
gl_date_format_2 = '%Y-%m'

gl_time_format = '%H:%M:%S'

one_choice_true_false = random.getrandbits(1)

消耗时间装饰器

"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
@email: [email protected]
"""


def spend_time_deco(func):
    def inner(*args, **kwargs):
        Log.info('')

        before = datetime.datetime.now()
        Log.info(before)

        res = func(*args, **kwargs)

        after = datetime.datetime.now()
        Log.info(after)

        spend = after - before
        Log.info(f'{func.__name__} 实际花费:{spend.total_seconds()}')

        Log.info('')

        return res

    return inner

读取配置文件

"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
@email: [email protected]
"""


def read_ini(ini_path: str = 'db.ini'):
    """
    读取配置文件
    :param ini_path:默认是数据库的配置文件
    :return:
    """

    if os.path.isfile(ini_path):
        config = ConfigParser()
        config.read(ini_path, encoding='UTF-8')

        return {cf: config.items(cf) for cf in config.sections()}

更新 传参dict

"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
@email: [email protected]
"""

def update_dict(local_dict: dict, params_name, params_value, body_dict):
    """

    :param local_dict:
    :param params_name:
    :param params_value:
    :param body_dict:
    :return:
    """
    if local_dict.get(params_name) is not None:
        body_dict.update({params_name: params_value})



    url = 'https://blog.csdn.net/zyooooxie'

    Log.info(locals())

    body = dict()
    update_dict(locals(), 'xie', xie, body)
    update_dict(locals(), 'blog', blog, body)

    req_dict = send_post_request_json(url=join_url(url), add_header=gl_header,
                                      params_dict=body)
    res = req_dict.get('obj')
    Log.info(res)
    

比较list、dict的元素

"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
@email: [email protected]
"""


def change_to_dict(data: Union[dict, list]) -> dict:
    """

    :param data:
    :return:
    """
    if not isinstance(data, dict):
        Log.debug('手动转换类型')

        try:
            data_dict = dict.fromkeys(data)

        except Exception as e:

            Log.debug(e.args)
            Log.debug(traceback.format_exc())

            data_dict = dict.fromkeys([str(d) for d in data])

    else:
        data_dict = data

    return data_dict


def compare_dict_key(dict1: Union[dict, list], dict2: Union[dict, list], assert_0: bool = False) -> list:
    """

    :param dict1:
    :param dict2:
    :param assert_0:
    :return:
    """
    dict1_ = change_to_dict(dict1)
    Log.error(len(dict1_))

    dict2_ = change_to_dict(dict2)
    Log.error(len(dict2_))

    not_in_list = list()

    for key in dict1_:
        if key not in dict2_:
            not_in_list.append(key)

    Log.error(f'在{id(dict1)},不在{id(dict2)}的数据 总共:{len(not_in_list)}条')
    Log.error(not_in_list)

    if assert_0:
        assert len(not_in_list) == 0

    return not_in_list


def compare_dict_key_value(dict1: dict, dict2: dict) -> dict:
    """

    :param dict1:
    :param dict2:
    :return:
    """

    not_in_dict = dict()

    for key, value in dict1.items():
        if key not in dict2 or value != dict2.get(key):
            not_in_dict.update({key: value})

    Log.error(f'在{id(dict1)},不在{id(dict2)}的数据 总共:{len(not_in_dict)}条')
    Log.error(not_in_dict)

    return not_in_dict

计算,获取date、time

"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
@email: [email protected]
"""


def get_newDate_newDateTime(old_date_time: str = None, **kwargs):
    """

    :param old_date_time:
    :param kwargs:
    :return:
    """
    # Log.info([i for i in datetime.timedelta.__dict__ if i.startswith('__') is False])
    Log.info(old_date_time)

    for k in kwargs.keys():
        assert k in ['days', 'seconds', 'minutes', 'hours', 'weeks']

    if not old_date_time:
        # 没传,取 当前的datetime
        odt = datetime.datetime.now()

    else:
        assert old_date_time.find(':') != -1
        assert old_date_time.find('-') != -1

        odt = datetime.datetime.strptime(old_date_time, gl_datetime_format)

    dt = odt + datetime.timedelta(**kwargs)
    Log.info(f'{dt}, {type(dt)}')

    timestamp_ = int(time.mktime(odt.timetuple()) * 1000)
    Log.info(f'{timestamp_}, {type(timestamp_)}')

    return odt, timestamp_

写入txt

"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
@email: [email protected]
"""

def write_txt(data: Union[str, list]):
    """
    写入文件(可一条一条写入,也可一次性全部写入)
    :param data:单独一条记录str   or  全部记录list
    :return:
    """
    file = r'D:\zyooooxie\param_{}.txt'.format(random.randint(1, 99999))
    Log.info(file)

    with open(file, mode='a', encoding='utf-8') as f:
        if isinstance(data, str):

            f.write(''.join([data, '\n']))

        elif isinstance(data, list):
            Log.info(len(data))
            w_data = list()

            for d in data:

                if type(d) == str:
                    ele = d
                else:
                    ele = ','.join([str(i) for i in d])

                w_data.append(''.join([ele, '\n']))

            f.writelines(w_data)

本文链接:https://blog.csdn.net/zyooooxie/article/details/127978957

个人博客 https://blog.csdn.net/zyooooxie

你可能感兴趣的:(Python脚本,python)