• python常用代码片段


    Python3常用

    文件处理

    
    class BaseMethod:
    
        @staticmethod
        def run_cmd(cmd):
            print_log("RUN CMD: %s" %cmd)
            retcode, output = subprocess.getstatusoutput(cmd)
            return retcode, output
    
        @staticmethod
        def write_file(filename, content):
            with tempfile.NamedTemporaryFile('w', dir=os.path.dirname(filename), delete=False) as tf:
                tf.write(content)
                tf.flush()
                tmpname = tf.name
            os.rename(tmpname, filename)
    
        @staticmethod
        def read_file_with_json(file_name, mode="r"):
            if not os.path.exists(file_name):
                raise IOError("No such file or directory: %s" % file_name)
            with open(file_name, mode) as fp:
                json_body = json.load(fp)
            return json_body
    
        @staticmethod
        def write_json_to_file(file_name, json_body, mode="w+"):
            # json_body 要求是字典
            with tempfile.NamedTemporaryFile(mode, dir=os.path.dirname(file_name), delete=False) as fp:
                json_str = json.dumps(json_body, indent=4, sort_keys=True)
                fp.write(json_str)
                fp.flush()
                temp_name = fp.name
            os.rename(temp_name, file_name)
    
        @staticmethod
        def json_file_format(source_filename, dest_filename):
            json_body = BaseMethod.read_file_with_json(source_filename)
            BaseMethod.write_json_to_file(dest_filename, json_body)
    

    json处理

    class FileBaseClass():
        @staticmethod
        def read_file_with_json(file_name, mode="r"):
            if not os.path.exists(file_name):
                raise IOError("No such file or directory: %s" % file_name)
            with open(file_name, mode) as fp:
                json_body = json.load(fp)
            return json_body
    
        @staticmethod
        def write_json_to_file(file_name, json_body, mode="w+"):
            with tempfile.NamedTemporaryFile(mode, dir=os.path.dirname(file_name), delete=False) as fp:
                json_str = json.dumps(json_body, indent=4, sort_keys=True)
                fp.write(json_str)
                fp.flush()
                temp_name = fp.name
            os.rename(temp_name, file_name)
    
        @staticmethod
        def json_file_format(source_filename, dest_filename):
            json_body = FileBaseClass.read_file_with_json(source_filename)
            FileBaseClass.write_json_to_file(dest_filename, json_body)
    
    
    

    log日志

    import argparse
    import os
    import shutil
    import json
    import logging
    import subprocess
    import tempfile
    import traceback
    from spec_template import spec_template
    
    log = logging.getLogger(__name__)
    log.setLevel(level=logging.INFO)
    handler = logging.FileHandler("rpm_build.log")
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    log.addHandler(handler)
    
    log.info("enter rpmbuild_core ...")
    
    

    argparse使用

    def main():
        usg = """
            python3 rpmbuild_core.py -r $ROOT_DIR -n BSWM -c arm32A15le_4.4_ek_preempt -f relative_file_path
    
        """
    
        parser = argparse.ArgumentParser(prog=__file__, formatter_class=argparse.RawDescriptionHelpFormatter,
                                         description=usg)
    
        parser.add_argument('-r', '--rootdir', nargs=1, help='必选,root工作目录ROOT_DIR')  # 返回的是list
        parser.add_argument('-n', '--compname', nargs='+', default='BSWM', help='可选,指定组件名称')
        parser.add_argument('-c', '--cputype', nargs='+', default='x86_64', help='可选,指定cpu类型')
        parser.add_argument('-f', '--file_path', nargs='?', default='', help='可选,指定额外的json文件,需要个人维护。value值为当前ROOT_DIR的相对目录')
    
        args = parser.parse_args()
        try:
            root_dir = args.rootdir[0]
            comp_name = args.compname[0]
            cpu_type = args.cputype[0]
            extra_file_path = args.file_path
            print('root_dir: %s, comp_name: %s, cpu_type: %s' % (root_dir, comp_name, cpu_type))
            main_func(root_dir, comp_name, cpu_type, extra_file_path)
    
        except Exception:
            traceback.print_exc()
            print('Please use -h/--help to get usage!')
            exit(1)
        log.info("leave rpmbuild_core success.")
    
    
    if __name__ == '__main__':
        main()
    
    

    INIparser

    这个还很不完善,仅供参考。

    class INIparser(object):
    
        def __init__(self, input_file):
    
            self.input = input_file
            self.output = self.input
    
        def get_target_key(self, sect, key):
            conf = configparser.ConfigParser()
            conf.read(self.input, encoding='utf-8')
            if sect in conf.sections():
                return conf[sect].get(key)
            return ""
    
        def add_section(self, sect):
            conf = configparser.ConfigParser()
            conf.read(self.input, encoding='utf-8')
            if sect in conf.sections():
                return
            else:
                conf.add_section(sect)
                with open(self.output, 'w', encoding='utf-8') as fp:
                    conf.write(fp)
    
        def add_target_key(self, sect, k_with_v):
            temp_list = k_with_v.split('=')
            key, value = temp_list[0], temp_list[1]
            conf = configparser.ConfigParser()
            conf.read(self.input)
            if sect not in conf.sections():
                conf.add_section(sect)
            conf.set(sect, key, value)
            with open(self.output, 'w') as fp:
                conf.write(fp)
    
        def rm_target_key(self, sect, key):
            conf = configparser.ConfigParser()
            conf.read(self.input, encoding='utf-8')
            if sect in conf.sections():
                conf.remove_option(sect, key)
                with open(self.output, 'w', encoding='utf-8') as fp:
                    conf.write(fp)
    
        def rm_target_section(self, sect):
            conf = configparser.ConfigParser()
            conf.read(self.input, encoding='utf-8')
            t = conf.remove_section(sect)
            print(t)
            with open(self.output, 'w', encoding='utf-8') as fp:
                conf.write(fp)
    
    

    文件或目录的相关操作

    
    
  • 相关阅读:
    convert data to numeric element wise , python,pandas
    return sql ret
    kettle学习
    kettle异常
    c# + python
    mysql表是否存在
    python configparser
    pandas sql execute
    apply map applymap
    sql 2008 中不能创建数据库关系图
  • 原文地址:https://www.cnblogs.com/jkhere/p/10785002.html
Copyright © 2020-2023  润新知