Press "Enter" to skip to content

Category: 编程学习

编程知识学习与进阶

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

python备份远程FTP脚本

自己写的一个Linux上使用python备份远程FTP脚本,编写此脚本的初衷是为了方便一些使用虚拟主机的朋友,因为许多虚拟主机商不提供备份服务,导致文件丢失的情况时有发生,因此就有了这个脚本。

系统需要安装fuse-curlftpfs、zlib、zlib-devel三个软件包,其中fuse-curlftpfs包不好安装,得先安装个第三方的yum源,才可以通过yum的方式安装之。

原理比较简单,即是python调用shell命令把远程FTP服务器挂载至本地,再打包压缩实现备份,最后解除挂载。备份以后的文件名会包含了备份的日期,同时会删除5天前备份的文件,配合crontab使用,可以实现定期备份FTP服务器上的文件。

如果是在VPS上使用,请确保VPS是不是基于Openvz虚拟化技术的,因为Openvz会限制对fuse的使用,无法实现远程挂载。Xen,KVM可以正常使用。

编写脚本期间还得到了zhiwei同学的帮助,在此提出感谢。脚本具备扩展性,可以备份多个FTP服务器上的目录。如果需要备份多个FTP,把脚本最后4行复制一遍即可。

使用方法:

Leave a Comment

python读取系统信息

python读取系统信息的一些方法

最主要是的platform模块:

>>> import platform
>>> platform.version()
'#1 SMP Fri Feb 22 00:31:26 UTC 2013'
>>> platform.platform()
'Linux-2.6.32-358.el6.x86_64-x86_64-with-centos-6.4-Final'
>>> platform.system()
'Linux'
>>> platform.machine()
'x86_64'
>>> platform.python_build()
('r266:84292', 'Feb 22 2013 00:00:18')
>>> platform.python_version()
'2.6.6'
>>> platform.release()
'2.6.32-358.el6.x86_64'
>>> platform.uname()
('Linux', 'localhost.localdomain', '2.6.32-358.el6.x86_64', '#1 SMP Fri Feb 22 00:31:26 UTC 2013', 'x86_64', 'x86_64')
>>> platform.architecture()
('64bit', 'ELF')
在windows上,专门还有个platform.win32_ver() 可用
Leave a Comment