python编程小技巧

一. 获取当前模块的类名

#coding:utf-8
import sys

class People():
    def __init__(self, name):
        print "name:", name
        print "*"*30
        print "class_name:", self.__class__.__name__

if __name__ == "__main__":
    p = People("zhangsan")

运行结果

name: zhangsan
******************************
class_name: People

二. 监控函数的运行

#coding:utf-8
import sys

def fun_1(name, age):
    print "name: %s, age: %s" %(name, age)

def fun_2(school):
    print "school: %s" %(school)

def run_fun(fun_name, *arg):
    try:
        fun_name(*arg)
    except Exception,e:
        print "error\t error_type=%s\t error_info=%s" %(fun_name.__name__, repr(e))

if __name__ == "__main__":
    run_fun(fun_1, "zhangsan", 29)
    run_fun(fun_2, "Henan Politecnic University")
    run_fun(fun_2, "Henan Politecnic University", "test")

运行结果

name: zhangsan, age: 29
school: Henan Politecnic University
error	 error_type=fun_2	 error_info=TypeError('fun_2() takes exactly 1 argument (2 given)',)

三. split分割字符串

str.split(str="", num=string.count(str))

参数:

  • str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • num – 分割次数。默认为 -1, 即分隔所有。

返回值:返回分割后的字符串列表。

示例:

print "hehe nlj 20".split(" ")
print "hehe nlj 20".split(" ", 1)

运行结果

['hehe', 'nlj', '20']
['hehe', 'nlj 20']

四. 写文件的两种方法

示例

#coding:utf-8
import sys

f = open("write.txt", "w")
my_str = "hello world !!!"
#方法1:
f.write(my_str+"\n")
#方法2:
print >> f, my_str

运行结果:

以上两种方法的效果一样

hello world !!!
hello world !!!

五. 加载不同类型的配置文件

示例

目录结构如下:

|—load_conf.py

| ----conf

​ |----test_1.json

​ |----test_2.json

​ |----test_3.cfg

test_1.json

[
"Demo1Feature",
"Demo2Feature",
"Demo3Feature"
]

test_2.json

{
  "ug_model":
  {
    "name":"ug_model",
    "feature_name":[1021001003, 1021401001, 1021001004, 1021401002]
  },
  "outlier_model":
  {
    "name":"outlier_model",
    "feature_name":[1031001003, 1031401001, 1031001004, 1031401002]
  }
}

test_3.cfg

[default]
name="zhangsan"
age="30"
school="Henan Politecnic University"

load_conf.py代码

#coding:utf-8
import json
import glob
import re
import sys
import ConfigParser

def load_json():
    featurelib_conf_dir = "conf"
    featurelib_conf_suffix_extension = ".json"
    for feature_lib_conf_file in glob.glob(featurelib_conf_dir+'/*'+ featurelib_conf_suffix_extension):
        with open(feature_lib_conf_file, 'r') as f:
            feature_production_conf = json.loads(re.sub('(\/\/.*)', '', re.sub('(/\*(.*?)\*/)', '', f.read(), flags=re.S)))
            print feature_lib_conf_file, "*"*30, type(feature_production_conf)
            if isinstance(feature_production_conf, list):
                for k in feature_production_conf:
                    print k
            elif isinstance(feature_production_conf, dict):
                for k,v in feature_production_conf.items():
                    print k,v
def load_cfg():
    conf_dir = "conf"
    conf_suffix_extension = ".cfg"
    for conf_file in glob.glob(conf_dir+'/*'+conf_suffix_extension):
        print "conf_file:", conf_file, "*"*30
        cfg = ConfigParser.ConfigParser()
        cfg.read(conf_file)
        sections = cfg.sections()
        for section in sections:
            print "section:", section, "+"*20
            for k,v in cfg.items(section):
              print k,"-->", v

if __name__ == "__main__":
    load_json()
    load_cfg()

运行结果:

conf/test_1.json ****************************** <type 'list'>
Demo1Feature
Demo2Feature
Demo3Feature
conf/test_2.json ****************************** <type 'dict'>
outlier_model {u'feature_name': [1031001003, 1031401001, 1031001004, 1031401002], u'name': u'outlier_model'}
ug_model {u'feature_name': [1021001003, 1021401001, 1021001004, 1021401002], u'name': u'ug_model'}
conf_file: conf/test_3.cfg ******************************
section: default ++++++++++++++++++++
name --> "zhangsan"
age --> "30"
school --> "Henan Politecnic University"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值