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. solr之创建core(搜索核心,包括索引和数据)的方法

    我的solrhome为D:\solrHome\solr step1:进入solrHome会看到collection1文件夹,创建该文件夹的副本,重命名为product 进入product文件夹,进入d ...

  2. asp.net query string 及 form data 遇到的编码问题

    当遇到此问题时,脑海里闪过的第一个解决方案是设置 web.config 的编码.但一想,就某一个页面的需求而导致其他跟着妥协,不是好的解决方案.于是网上搜索答案,下面做个小分享,遗憾的是研究不够深入, ...

  3. 自定义注解与validation结合使用案例

    编写validation自定义注解: @Target({ ElementType.FIELD, ElementType.METHOD })@Retention(RetentionPolicy.RUNT ...

  4. PHP函数gmstrftime()将秒数转换成天时分秒

    http://yangjunwei.com/a/930.html PHP函数gmstrftime()将秒数转换成天时分秒   一个应用场景需要用到倒计时的时分秒,比如新浪微博授权有效期剩余: 7天16 ...

  5. devexpress 的combobox怎样只能选择不能输入

    我们知道listbox和combobox的区别就是listbox是下拉列表框,只能下拉,不支持在listbox中自定义输入,而combobox是textbox和listbox的合体,被称为组合框. c ...

  6. vue中文章的折叠于显示全部

    在以一篇文章中,可能文章特别长,但是在页面第一次显示的时候可能就只需要显示一部分,这种情况下就需要自己进行修改 基本思路 利用类名就是预先定义一个类名,设置高度,和overflow:hidden,前提 ...

  7. 第21章:MongoDB-聚合操作--聚合管道--$geoNear

    ①$geoNear 使用“$geoNear”可以得到附近的坐标点. ②范例:准备测试数据

  8. Apache 2.4.28的安装

    Apache 2.4.28的安装 1.安装Apache 1.1下载Apache网址:http://httpd.apache.org/ [root@localhost ~]# mkdir -p /roo ...

  9. Redis集群master选举时长测试

    在一台物理机上启动6个Redis实例,组成3主3从集群,端口号依次为:1379 ~ 1384,端口号1379.1380和1384三个为master,端口1379的进程ID为17620.现将进程1762 ...

  10. 【ORA错误大全】 ORA-19527

    在做主备切换的时候,需要将备库的联机日志文件清除(clear online redo logfile),为了加快switchover的速度,Oracle10g在将备库置于manged standby状 ...