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)
文件或目录的相关操作
python常用代码片段的更多相关文章
- Python 常用 代码片段
文件名字中含有特殊字符转成空格,因为?‘’等作为文件名是非法的.以下正则表达式进行过滤转换 newname = re.sub("[\s+\.\!\/_,$%^*(+\"\')]+| ...
- C#常用代码片段备忘
以下是从visual studio中整理出来的常用代码片段,以作备忘 快捷键: eh 用途: 类中事件实现函数模板 private void MyMethod(object sender, Event ...
- 36个Android开发常用代码片段
//36个Android开发常用代码片段 //拨打电话 public static void call(Context context, String phoneNumber) { context.s ...
- Jquery学习总结(1)——Jquery常用代码片段汇总
1. 禁止右键点击 ? 1 2 3 4 5 $(document).ready(function(){ $(document).bind("contextmenu",fun ...
- 【转载】GitHub 标星 1.2w+,超全 Python 常用代码合集,值得收藏!
本文转自逆袭的二胖,作者二胖 今天给大家介绍一个由一个国外小哥用好几年时间维护的 Python 代码合集.简单来说就是,这个程序员小哥在几年前开始保存自己写过的 Python 代码,同时把一些自己比较 ...
- jQuery常用代码片段
检测IE浏览器 在进行CSS设计时,IE浏览器对开发者及设计师而言无疑是个麻烦.尽管IE6的黑暗时代已经过去,IE浏览器家族的人气亦在不断下滑,但我们仍然有必要对其进行检测.当然,以下片段亦可用于检测 ...
- Vue3.0常用代码片段和开发插件
Vue3 Snippets for Visual Studio Code Vue3 Snippets源码 Vue3 Snippets下载 This extension adds Vue3 Code S ...
- python 常用代码
获取标签名 h1 class 是h1usersoup.find(name="h1", attrs={"class":"h1user"});获 ...
- Ext.NET Ext.JS 常用代码片段摘录
引言 最近写代码突然有"一把梭"的感觉, 不管三七二十一先弄上再说. 换别人的说法, 这应该是属于"做项目"风格法吧. 至于知识体系, 可以参考官方或者更权威的 ...
随机推荐
- 使用EventLog Analyzer监控、管理及分析日志
- windows下mongodb安装与使用图文教程(整理)
一.首先安装mongodb 1.下载地址:http://www.mongodb.org/downloads 2.解压缩到自己想要安装的目录,比如d:\mongodb 3.创建文件夹d:\mongodb ...
- linux vi操作
1.“i”键,进入编辑状态.可以看到命令的下方出现了“--INSERT--”字样,表示成功进入了编辑模式; 2.“Esc”键,退出编辑模式.并在此时输入“:wq”以退出并保存
- 安装SourceTree遇到的一个个坑
之前在公司的电脑上满心欢喜的安装了下,很顺利就成功了,回来在自己电脑上安装,结果坑不能停,以此来纪念下吧! 下载完成后,进行安装: 这里我是申请了个账户,选第一个user an existing ac ...
- php 类与对象 面向对象编程 简单例子
<?php class Foo { //类 名称为Foo public $aMemberVar = 'aMemberVar Member Variable'; //类变量 public $aFu ...
- javase jdk 环境变量 涵义
jdk环境变量配置:path:jdk安装所在目录下的bin路径-->因为环境变量path下放置的是操作系统执行的.exe文件,jdk中bin中放的是可执行的.exe文件,所以要把这个路径放置到p ...
- Switch 选择结构
switch 选择器 一.语法 switch(变量名){ case 情况1: //代码块 break: case 情况1: //代码块 break: default(默认): //代码块 break: ...
- 深入浅出javascript(四)网页运行原理
这一篇是根据不同的书本知识归纳的内容,解答的问题是浏览器是如何工作的? 另外,还有一些长篇的内容,写的是浏览器内部如何架构的,这些内容非常复杂艰深,比现在所写的内容又低了一个层级,希望有时间能总结贴出 ...
- 分形在遥感和GIS中的应用
GIS等高线化简 遥感图像的追踪 分形matlab实现:分形应用于遥感图像处理 低分辨率和高分辨率图形它们的形状是相似的(图像增强) 贪吃蛇和蚁群算法:试想管中窥豹,一只小蚂蚁 ...
- php获取跳转后的真实链接
网站的跳转链接经常为本站链接加上一些参数来跳转,如何使用php获取跳转后的链接呢? php代码如下: <?php // echo get_redirect_url('http://www.osc ...