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. win8 本地化

    先看个简单的案例:新时尚Windows8开发(6):资源 & 本地化 http://www.silverlightchina.net/html/windows8/study/2012/0902 ...

  2. MySQL按日、周、月统计数据

    知识关键词:DATE_FORMAT ps:如果时间字段为时间戳则,DATE_FORMAT(from_unixtime(create_time),'%Y-%u') select DATE_FORMAT( ...

  3. (6)How language shapes the way we think

    https://www.ted.com/talks/lera_boroditsky_how_language_shapes_the_way_we_think/transcript 00:12So, I ...

  4. (2)The secrets of learning a new language

    https://www.ted.com/talks/lydia_machova_the_secrets_of_learning_a_new_language/transcript 00:13I lov ...

  5. (1)There's more to life than being happy

    https://www.ted.com/talks/emily_esfahani_smith_there_s_more_to_life_than_being_happy00:12 I used to ...

  6. jquery checkbox反复调用attr('checked', true/false)只有第一次生效 Jquery 中 $('obj').attr('checked',true)失效的几种解决方案

    1.$('obj').prop('checked',true) 2. $(':checkbox').each(function(){ this.checked=true; }) 为什么:attr为失效 ...

  7. 修改oracle用户密码为永不过期

    错误提示:ORA-28001: the password has expired (DBD ERROR: OCISessionBegin) 解决方法:修改密码为永不过期 (1)查看用户的proifle ...

  8. exec函数

    概念 当进程调用一种exec函数时,该进程执行的程序完全替换为新程序,新程序从main函数开始执行.调用exec并不创建新进程,所以前后的进程ID并未改变.exec只是用磁盘上的一个新程序替换了当前进 ...

  9. 第12章:MongoDB-CRUD操作--文档--查询--游标详解

    ①是什么游标 游标不是查询结果,可以理解为数据在遍历过程中的内部指针,其返回的是一个资源,或者说数据读取接口. 客户端通过对游标进行一些设置就能对查询结果进行有效地控制,如可以限制查询得到的结果数量. ...

  10. 安卓TP驱动开发

    转自 blog.csdn.net/dddxxxx/article/details/54312415