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)

文件或目录的相关操作


python常用代码片段的更多相关文章

  1. Python 常用 代码片段

    文件名字中含有特殊字符转成空格,因为?‘’等作为文件名是非法的.以下正则表达式进行过滤转换 newname = re.sub("[\s+\.\!\/_,$%^*(+\"\')]+| ...

  2. C#常用代码片段备忘

    以下是从visual studio中整理出来的常用代码片段,以作备忘 快捷键: eh 用途: 类中事件实现函数模板 private void MyMethod(object sender, Event ...

  3. 36个Android开发常用代码片段

    //36个Android开发常用代码片段 //拨打电话 public static void call(Context context, String phoneNumber) { context.s ...

  4. Jquery学习总结(1)——Jquery常用代码片段汇总

    1. 禁止右键点击 ? 1 2 3 4 5 $(document).ready(function(){     $(document).bind("contextmenu",fun ...

  5. 【转载】GitHub 标星 1.2w+,超全 Python 常用代码合集,值得收藏!

    本文转自逆袭的二胖,作者二胖 今天给大家介绍一个由一个国外小哥用好几年时间维护的 Python 代码合集.简单来说就是,这个程序员小哥在几年前开始保存自己写过的 Python 代码,同时把一些自己比较 ...

  6. jQuery常用代码片段

    检测IE浏览器 在进行CSS设计时,IE浏览器对开发者及设计师而言无疑是个麻烦.尽管IE6的黑暗时代已经过去,IE浏览器家族的人气亦在不断下滑,但我们仍然有必要对其进行检测.当然,以下片段亦可用于检测 ...

  7. Vue3.0常用代码片段和开发插件

    Vue3 Snippets for Visual Studio Code Vue3 Snippets源码 Vue3 Snippets下载 This extension adds Vue3 Code S ...

  8. python 常用代码

    获取标签名 h1 class 是h1usersoup.find(name="h1", attrs={"class":"h1user"});获 ...

  9. Ext.NET Ext.JS 常用代码片段摘录

    引言 最近写代码突然有"一把梭"的感觉, 不管三七二十一先弄上再说. 换别人的说法, 这应该是属于"做项目"风格法吧. 至于知识体系, 可以参考官方或者更权威的 ...

随机推荐

  1. C#调用开源图像识别类库tessnet2

    首先下载tessnet2_32.dll及相关语言包,将dll加入引用 private tessnet2.Tesseract ocr = new tessnet2.Tesseract();//声明一个O ...

  2. Idea中如何将web项目打包成war包并放到tomcat中启动

    第一步:在idea中选中Artifacts.右侧勾选Build on make生成war包,如下图 第二步:将target文件夹里面的war包拷贝到tomcat文件下的webapp目录下 第三步:修改 ...

  3. PHP获取手机号

    /** * 类名: mobile * 描述: 手机信息类 * 其他: 偶然 编写 */ class mobile{ /** * 函数名称: getPhoneNumber * 函数功能: 取手机号 * ...

  4. java正则表达式笔记

    import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntax ...

  5. springboot深入学习(四)-----tomcat配置、websocket

    一.更改servlet服务器 springboot中默认可以集成多种servlet容器,当引入如下依赖时: springboot默认以tomcat作为项目的servlet容器,如果用户想要替换tomc ...

  6. VC调试小结

    本机调试F5: 开始调试Shift+F5: 停止调试F10: 调试到下一句,这里是单步跟踪 F11: 调试到下一句,跟进函数内部Shift+F11: 从当前函数中跳出F9: 设置(取消)断点Outpu ...

  7. java常用设计模式三:原型模式

    在说原型模式之前先说一下浅拷贝和深拷贝的概念 一.浅拷贝和深拷贝 1.浅拷贝 在java中,对象创建后需要有一个引用变量来指向该对象实际的地址空间,也就是说引用变量与对象实体是两个不同的数据体.在Ob ...

  8. GAME PROGRAMM

    SetConsoleTextAttribute consolehwnd = GetStdHandle(STD_OUTPUT_HANDLE); GetStdHandle(nStdHandle)//是返回 ...

  9. mysql order by 中文 排序

    mysql order by 中文 排序 1. 在MySQL中,我们经常会对一个字段进行排序查询,但进行中文排序和查找的时候,对汉字的排序和查找结果往往都是错误的. 这种情况在MySQL的很多版本中都 ...

  10. 第14章:MongoDB-聚合操作--聚合管道

    ① 聚合管道是MongoDB2.2版本引入的新功能.它由阶段(Stage)组成,文档在一个阶段处理完毕后,聚合管道会把处理结果传到下一个阶段. 每个阶段用阶段操作符(Stage Operators)定 ...