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. SparkStreaming--reduceByKeyAndWindow

    1.reduceByKeyAndWindow(_+_,Seconds(3), Seconds(2))     可以看到我们定义的window窗口大小Seconds(3s) ,是指每2s滑动时,需要统计 ...

  2. 【转】先说IEnumerable,我们每天用的foreach你真的懂它吗?

    [转]先说IEnumerable,我们每天用的foreach你真的懂它吗? 我们先思考几个问题: 为什么在foreach中不能修改item的值? 要实现foreach需要满足什么条件? 为什么Linq ...

  3. 使用 IntelliTrace 调试应用程序

    IntelliTrace 如何能够大幅改善您的日常开发活动,并提升您快速轻松诊断问题的能力,而不必重新启动应用程序和使用传统的“中断-单步执行-检查”技术进行调试.介绍了组织如何能够通过在测试过程中收 ...

  4. JavaScript函数和内置对象

    一.函数 function f1(){ console.log("666"); } f1(); //调用函数 1.普通函数定义 function f1(a,b){ console. ...

  5. 2019.01.21 洛谷P3919 【模板】可持久化数组(主席树)

    传送门 题意简述:支持在某个历史版本上修改某一个位置上的值,访问某个历史版本上的某一位置的值. 思路: 用主席树直接维护历史版本即可. 代码: #include<bits/stdc++.h> ...

  6. 2019.01.19 codeforces893F.Subtree Minimum Query(线段树合并)

    传送门 线段树合并菜题. 题意简述:给一棵带点权的有根树,多次询问某个点ppp子树内距离ppp不超过kkk的点的点权最小值,强制在线. 思路: 当然可以用dfsdfsdfs序+主席树水过去. 然而线段 ...

  7. OSS 视频存储

    我这里加了 封面图片 可以不理睬! 我没有存oss. 阿里的OSS 自己可以去官网下载 我这里放到 Vendor 下的. 1 # 注意这里OSS中 请设置 存储空间名称为公共的 才能直接使用这里返回的 ...

  8. JPA错误

    2016-11-141.2016-10-31: hibernate用注解 一对多 报Could not determine type for错误 原因:  接下来继续解决第二个问题:怎么又与集合打交道 ...

  9. SQL语句关联查询

    一:连接类型: 关联查询:只有存在关联的表才能关联查询,完全独立的表之间无法关联 1.关联的类型:自关联,左关联,右关联,全关联(full join)两张表都是主表 2.关联的表:两张以上,以一张(或 ...

  10. WEB应用支持RESTFUL风格方法

    REST概念 Restful就是一个资源定位及资源操作的风格.不是标准也不是协议,只是一种风格.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制. REST风格 资源:互联网所有的事物 ...