Python杂七杂八

一、简介

      Python各方面的编程内容总结下来并不断更新,以便以后使用时查询。

二、详解

1、Python获取路径文件名

(1)split()函数进行字符串分割


 (2)basename()函数

2、Python下的SQlite数据库

       Python2.5集成了pysqlite数据库接口程序(sqlite3 模块),这是Python标准库第一次将一个数据库接口程序纳入标准库。
       SQLite操作的例子:
[html]  view plain  copy
  1. >>> import sqlite3  
  2. >>> cxn = sqlite3.connect('sqlite.db')  
  3. >>> cur = cxn.cursor()  
  4. >>> cur.execute('CREATE TABLE users(login VARCHAR(8), uid INTEGER)')  
  5. <sqlite3.Cursor object at 0x7f176e186710>  
  6. >>> cur.execute('INSERT INTO users VALUES("john", 100)')  
  7. <sqlite3.Cursor object at 0x7f176e186710>  
  8. >>> cur.execute('INSERT INTO users VALUES("jane", 110)')  
  9. <sqlite3.Cursor object at 0x7f176e186710>  
  10. >>> cur.execute('SELECT * FROM users')  
  11. <sqlite3.Cursor object at 0x7f176e186710>  
  12. >>> for eachUser in cur.fetchall():  
  13. ...     print eachUser  
  14. ...   
  15. (u'john', 100)  
  16. (u'jane', 110)  
  17. >>> cur.execute('DROP TABLE users')  
  18. <sqlite3.Cursor object at 0x7f176e186710>  
  19. >>> cur.close()  
  20. >>> cxn.commit()  
  21. >>> cxn.close()  
[html]  view plain  copy
  1. #!/usr/bin/env python  
  2.   
  3. import os  
  4. from random import randrange as rrange  
  5.   
  6. COLSIZ = 10  
  7. DB_EXC = None  
  8.   
  9. def connect(dbDir, dbName):  
  10.     global DB_EXC  
  11.     try:  
  12.         import sqlite3  
  13.     except ImportError, e:  
  14.         try:  
  15.             from pysqlite2 import dbapi2 as sqlite3  
  16.         except ImportError, e:  
  17.             return None  
  18.   
  19.     DB_EXC = sqlite3  
  20.     if not os.path.isdir(dbDir):  
  21.         os.mkdir(dbDir)  
  22.     cxn = sqlite3.connect(os.path.join(dbDir, dbName))  
  23.     return cxn  
  24.   
  25. def create(cur):  
  26.     try:  
  27.         cur.execute('''  
  28.             CREATE TABLE users (  
  29.                 login VARCHAR(8),  
  30.                 uid INTEGER,  
  31.                 prid INTEGER)  
  32.            ''')  
  33.     except DB_EXC.OperationalError, e:  
  34.         drop(cur)  
  35.         create(cur)  
  36.   
  37. drop = lambda cur: cur.execute('DROP TABLE users')  
  38.   
  39. NAMES = (  
  40.     ('aaron', 8312), ('angela', 7603), ('dave', 7306),  
  41.     ('davina',7902), ('elliot', 7911), ('ernie', 7410),  
  42.     ('jess', 7912), ('jim', 7512), ('larry', 7311),  
  43.     ('leslie', 7808), ('melissa', 8602), ('pat', 7711),  
  44.     ('serena', 7003), ('stan', 7607), ('faye', 6812),  
  45.     ('amy', 7209),  
  46. )  
  47.   
  48. def randName():  
  49.     pick = list(NAMES)  
  50.     while len(pick) > 0:  
  51.         yield pick.pop(rrange(len(pick)))  
  52.   
  53. def insert(cur):  
  54.     cur.executemany("INSERT INTO users VALUES(?, ?, ?)",  
  55.     [(who, uid, rrange(1,5)) for who, uid in randName()])  
  56.       
  57.   
  58. getRC = lambda cur: cur.rowcount if hasattr(cur, 'rowcount') else -1  
  59.   
  60. def update(cur):  
  61.     fr = rrange(1,5)  
  62.     to = rrange(1,5)  
  63.     cur.execute(  
  64.         "UPDATE users SET prid=%d WHERE prid=%d" % (to, fr))  
  65.     return fr, to, getRC(cur)  
  66.   
  67. def delete(cur):  
  68.     rm = rrange(1,5)  
  69.     cur.execute('DELETE FROM users WHERE prid=%d' % rm)  
  70.     return rm, getRC(cur)  
  71.   
  72. def dbDump(cur):  
  73.     cur.execute('SELECT * FROM users')  
  74.     print '%s%s%s' % ('LOGIN'.ljust(COLSIZ),  
  75.         'USERID'.ljust(COLSIZ), 'PROJ#'.ljust(COLSIZ))  
  76.     for data in cur.fetchall():  
  77.         print '%s%s%s' % tuple([str(s).title().ljust(COLSIZ) \  
  78.             for s in data])  
  79.   
  80. def main():  
  81.     print '*** Connecting to sqlite database'  
  82.     cxn = connect('sqlitedir', 'test.db')  
  83.     if not cxn:  
  84.         print 'ERROR: %r not supported, exiting' % db  
  85.         return  
  86.     cur = cxn.cursor()  
  87.   
  88.     print '*** Creating users table'  
  89.     create(cur)  
  90.   
  91.     print '*** Inserting names into table'  
  92.     insert(cur)  
  93.     dbDump(cur)  
  94.   
  95.     print '*** Randomly moving folks',  
  96.     fr, to, num = update(cur)  
  97.     print 'from one group (%d) to another (%d)' % (fr, to)  
  98.     print '\t(%d users moved)' % num  
  99.     dbDump(cur)  
  100.   
  101.     print '*** Randomly choosing group',  
  102.     rm, num = delete(cur)  
  103.     print '(%d) to delete' % rm  
  104.     print '\t(%d users removed)' % num  
  105.     dbDump(cur)  
  106.   
  107.     print '*** Dropping users table'  
  108.     drop(cur)  
  109.     cur.close()  
  110.     cxn.commit()  
  111.     cxn.close()  
  112.   
  113. if __name__ == '__main__':  
  114.     main()  

3、print函数输出

[html]  view plain  copy
  1. >>> str = 'hello world'  
  2. >>> print str  
  3. hello world  
  4. >>> print 'length of (%s) is %d' %(str, len(str))  
  5. length of (hello world) is 11  
  6. >>> hex = 0xFF  
  7. >>> print 'hex = %x, dec = %d, oct=%o' % (hex, hex, hex)  
  8. hex = ffdec = 255oct=377  
  9. >>> import math  
  10. >>> print 'pi = %10.3f' % math.pi  
  11. pi =      3.142  
  12. >>> print 'pi = %-10.3f' % math.pi  
  13. pi = 3.142       
  14. >>> print 'pi = %06d' % int(math.pi)  
  15. pi = 000003  
  16. >>> precise = 4  
  17. >>> print ("%.*s" % (4,"python"))  
  18. pyth  
  19. >>> print ("%10.3s " % ("python"))  
  20.        pyt   
  21. >>> lst = [1,2,3,4,'python']  
  22. >>> print lst  
  23. [1, 2, 3, 4, 'python']  
  24. >>> for i in range(0,6):  
  25. ...     print i,  
  26. ...   
  27. 0 1 2 3 4 5  
  28. >>> import sys  
  29. >>> sys.stdout.write('hello world\n')  
  30. hello world  

4、Python中文支持

添加一行声明文件编码的注释(python默认使用ASCII编码),必须将编码注释放在第一行或者第二行。

[html]  view plain  copy
  1. # -*- coding:utf-8 -*-    
或者
[html]  view plain  copy
  1. #coding=utf-8   
Windows下使用:
[html]  view plain  copy
  1. #coding=gbk  
  2. # -*- coding: gbk -*-  

5、将python的py文件编译成保密的pyc文件

        由于python程序的py文件很容易泄露源代码,所以python可以编译成保密的pyc文件。python的pyc文件是一种二进制文件,py文件变成pyc文件后,加载的速度有所提高,而且pyc是一种跨平台的字节码,是由python的虚拟机来执行的,这个是类似于JAVA或者.NET的虚拟机的概念。
        编pyc文件也是可以反编译的,不同版本编译后的pyc文件是不同的,根据python源码中提供的opcode,可以根据pyc文件反编译出py文件源码,网上可以找到一个反编译python2.3版本的pyc文件的工具,不过该工具从python2.4开始就要收费了,如果需要反编译出新版本的pyc文件的话,就需要自己动手了,不过你可以自己修改python的源代码中的opcode文件,重新编译python,从而防止不法分子的破解。
       (1)编译py文件到pyc文件的方法:在命令行输入:python -m py_compile myFile.py 就可以生成对应的pyc文件了(有时会将pyc的后缀改为py,通过file命令可以看出为byte-compiled)。
       (2)内置的类库来实现把py文件编译为pyc文件,这个模块就是py_compile模块。
生成单个pyc文件:

[html]  view plain  copy
  1. import py_compile  
  2. py_compile.compile(r'/tmp/test.py')  
compile函数原型:compile(file[, cfile[, dfile[, doraise]]])
file:表示需要编译的py文件的路径
cfile:表示编译后的pyc文件名称和路径,默认为直接在file文件名后加c 或者 o,o表示优化的字节码
dfile:这个参数英文看不明白,请各位大大赐教。(鄙视下自己)原文:it is used as the name of the source file in error messages instead of file
doraise:可以是两个值,True或者False,如果为True,则会引发一个PyCompileError,否则如果编译文件出错,则会有一个错误,默认显示在sys.stderr中,而不会引发异常
批量生成pyc文件:
        若工程都是在一个目录下的,一般不会说仅仅编译一个py文件而已,而是需要把整个文件夹下的py文件都编译为pyc文件,python又提供了另一个模块:compileall 。使用方法如下:
[html]  view plain  copy
  1. import compileall  
  2. compileall.compile_dir(r'/tmp/code/')  
这样就把/tmp/code目录,以及其子目录下的py文件编译为pyc文件了。
compile_dir函数的说明:compile_dir(dir[, maxlevels[, ddir[, force[, rx[, quiet]]]]])
dir:表示需要编译的文件夹位置
maxlevels:表示需要递归编译的子目录的层数,默认是10层,即默认会把10层子目录中的py文件编译为pyc
ddir:it is used as the base path from which the filenames used in error messages will be generated。
force:如果为True,则会强制编译为pyc,即使现在的pyc文件是最新的,还会强制编译一次,pyc文件中包含有时间戳,python编译器会根据时间来决定,是否需要重新生成一次pyc文件
rx:表示一个正则表达式,比如可以排除掉不想要的目录,或者只有符合条件的目录才进行编译
quiet:如果为True,则编译后,不会在标准输出中,打印出信息。
代码片段:
[html]  view plain  copy
  1. #-*- coding=utf-8  
  2. '''  
  3. #编译目录下所有py文件为 pyc文件  
  4. import compileall  
  5. compileall.compile_dir(r"/tmp/code/")  
  6. '''  
  7. #编译 单个py文件为 pyc文件  
  8. import py_compile  
  9. py_compile.compile(r"/tmp/code/test.py")  

########################3

转自:http://blog.csdn.net/taiyang1987912/article/details/40383641

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值