Press "Enter" to skip to content

Category: 编程学习

编程知识学习与进阶

Python读取配置文件模块ConfigParser

1,ConfigParser模块简介
假设有如下配置文件,需要在Pyhton程序中读取

$ cat config.ini
[db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = xgmtest

[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True

[SectionTwo]
FavoriteColor = Green
[SectionThree]
FamilyName: Johnson

[Others]
Route: 66

如何在Python中读取呢

>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("config.ini")
['config.ini']
>>> Config.sections()
['db', 'Others', 'SectionThree', 'SectionOne', 'SectionTwo']
>>> Config.get("db", "db_host")
'127.0.0.1'
>>> Config.getint("db", "db_port")
3306
4 Comments

使用pytest进行批量测试

Pytest是python的一个测试模块,可以编写一些简单的测试用例,也可以用来进行一些批量测试,下面简单介绍一下。

1,安装

$ pip install -U pytest
or
$ easy_install -U pytest

$ py.test --version

2,基础语法
[code lang=”python”]
#!/usr/bin/python
import pytest

def func(x):
return x + 1

def test_answer(): #测试用例,方法需要以test_开头
assert func(3) == 5

运行之

$ py.test 2.py    #注意需要用py.test命令来运行之

稍微复杂一点儿的写法:
[code lang=”python”]
#!/usr/bin/python
import pytest

class TestClass:

def test_one(self):
x = "this"
assert "h" in x

def test_two(self):
x = 3
assert x > 2

Leave a Comment

Python tips – 轻松转换列表与字符串

There are a few useful tips to convert a Python list (or any other iterable such as a tuple) to a string for display.

First, if it is a list of strings, you may simply use join this way:

>>> mylist = ['spam', 'ham', 'eggs']
>>> print ', '.join(mylist)
spam, ham, eggs

Using the same method, you might also do this:

>>> print '\n'.join(mylist)
spam
ham
eggs

However, this simple method does not work if the list contains non-string objects, such as integers.

If you just want to obtain a comma-separated string, you may use this shortcut:

>>> list_of_ints = [80, 443, 8080, 8081]
>>> print str(list_of_ints).strip('[]')
80, 443, 8080, 8081

Or this one, if your objects contain square brackets:

>>> print str(list_of_ints)[1:-1]
80, 443, 8080, 8081

Finally, you may use map() to convert each item in the list to a string, and then join them:

>>> print ', '.join(map(str, list_of_ints))
80, 443, 8080, 8081
>>> print '\n'.join(map(str, list_of_ints))
80
443
8080
8081
Leave a Comment

python遍历文件脚本实例

自己写的一个Python遍历文件脚本,对查到的文件进行特定的处理。没啥技术含量,但是也记录一下吧。

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import shutil
dir = "/mnt/Packages"
class Packages:
    def __init__(self,srcdir,desdir):
        self.sdir=srcdir
        self.ddir=desdir
    def check(self):
        print('program start...')
        for dirpath, dirnames, filenames in os.walk(self.sdir):   #遍历文件
            for filename in filenames:
                thefile=os.path.join(dirpath,filename)            #文件的绝对地址
                try:
                    if os.path.splitext(thefile)[1]=='.rpm':      #筛选.rpm格式的文件
                        #print('Fount rpm package: ' + thefile)
                        if 'inspuer' in os.popen('rpm -qpi ' + thefile).read().rstrip():
                            print('Found error package: ' + thefile)
                            shutil.copy(thefile, self.ddir)  #将错误文件复制到desdir目录
                            f = open('list.txt', 'a')    #将错误文件列表写入到list.txt
                            f.write(filename + '\n')
                            f.close()
                except IOError, err:
                    print err
                    sys.exit()

if __name__ == '__main__':
    dir=Packages('/mnt/cdrom','/mnt/erpm')   #源目录为/mnt/cdrom,目标目录为/mnt/erpm
    dir.check()
Leave a Comment

Python re正则匹配中文

Python re正则匹配中文,其实非常简单,把中文的unicode字符串转换成utf-8格式就可以了,然后可以在re中随意调用将输入的utf-8中文解密为unicode,然后交由python处理(2014.10.09感谢QQ85897930纠正)。

unicode中中文的编码为/u4e00-/u9fa5,因此正则表达式u”[\u4e00-\u9fa5]+”可以表示一个或者多个中文字符

>>> import re

>>> s='中文:123456aa哈哈哈bbcc'.decode('utf8')
>>> s
u'\u4e2d\u6587\uff1a123456aa\u54c8\u54c8\u54c8bbcc'
>>> print s
中文:123456aa哈哈哈bbcc

>>> re.match(u"[\u4e00-\u9fa5]+",s)
<_sre.SRE_Match object at 0xb77742c0>

>>> pat='中文'.decode("utf8")
>>> re.search(pat,s)
<_sre.SRE_Match object at 0x16a16df0>

>>> newpat='这里是中文内容'.decode("utf8")

>>> news=re.sub(pat,newpat,s)
>>> print news
这里是中文内容:123456aa哈哈哈bbcc
2 Comments

安装Pyhton MySQLdb

安装很简单,几步就好

wget -q http://peak.telecommunity.com/dist/ez_setup.py
python ./ez_setup.py

wget http://downloads.sourceforge.net/project/mysql-python/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz
tar -zxvf MySQL-python-1.2.3.tar.gz 
cd MySQL-python-1.2.3
python setup.py install

可能出现问题1:error: command ‘gcc’ failed with exit status 1
解决:yum install python-devel

Leave a Comment

python中文件的复制

文件的复制
file类中没有提供专门的文件复制函数,因此只能通过使用文件的读写函数来实现文件的复制。这里仅仅给出范例:

src = file("myfile.txt", "w+")
temp = ["hello world! \n"]
src.writelines(temp)
src.close()

src = file("myfile.txt", "r+")
des = file("myfile2.txt", "w+")
des.writelines(src.read())
src.close()
des.close()
Leave a Comment