# python def test(): 3 ** 3 # 三的三次方 3 % 2 # 三与二求余操作 a = 1 type a # type用来查看一个变量的类型 g = lambda x,y:x ** y # python允许定义一个单行的小程序 g( 3 , 4 ) # 实际进行的是:后的程序脚本 def appaendmethon(): a = [ ' 1 ' , ' 2 ' ] # print len(a) for n in range(len(a)): # print a[n] temp = str(a[n]) temp = temp + " a " # a = [] # a = temp # print a a[n] = temp a1,a2 = 1 , 2 b = [a1,a2] print b print a def ifnotmethod(): if not a == 0: print " test1 " else : print " test2 " import sys def path_append_class(): sys.path.append( " c:/path " ) def Raw_inputmethod(): name = raw_input( " please input the value 's : " ) print " value: " + name def mysql_version(): # cd /mysql/bin # ./mysql --help # ./mysqladmin version 第一种方法 # ./mysql -uroot -p -e "select version" 第二种方法 # 一次性执行mysql语句,./mysql -uroot -p -e(操作符) "sql find conditionn" def msyql_create_view(): # 把多个表放入一个静态视图,进行操作,锁定操作权限,抽象为较为简单的数据模型,便于查询 # create view AB as selct sid,name as sid,name from A,select count,pid as count,pid from B; # 筛选一段数据生成一个视图,create view test as select name as name from acount where name >= '123' and name <='456'; # 删除一个视图:drop view test; def mysql_show_table_status(): # 查看当前所有表的,数据大小 # show table status # mysql表通常存在,最大限制一般决定于操作系统,例如:Linux上,mysql单表的最大限制是2G; # Windows上,mysql单表的最大限制4G def dictionary(): d = { " 3 " : " 4 " , " 4 " : " 5 " } # 修改字典 d[ " 3 " ] = " 5 " # 追加元素 d[ " 6 " ] = " 6 " # 重复的关键字会被覆盖 # 删除一个元组 del d[ " 3 " ] # 清楚字典 d.clear() # 查询字典的索引,如果有则返回ture d.has_key(exist_index) # 查询一个值是否存在于字典对应的索引对象中,如果有则返回ture value in d[index] value not in d[index] # 复制一个字典 value = d.copy() # 把字典分割成一个数组,按照索引分割为一个元组 d.items() # 按照索引的值更新一个字典,[b]要求为两位字符串 d.update([b]) d.update([ ' 12 ' ]) # 生成一个新的字典 d = d.fromkeys( ' 2 ' , ' ddddddd ' ) # 得到一个字典所有索引对象值的数组 d.values() # 得到索引的值 d.get(index,None) # 建立索引,追加索引 d.setdefault(index,value) # 根据索引删除值 d.pop(index) # 删除第一个索引和值,并返回删除的value and index d.popitem() def list(): # 数组 list = [ " 1 " , " 2 " , " 3 " , " 4 " ] # 最后一个值 list[ - 1 ] # 数组的分段,list[1]=2,list[2]=3,结果为2,3 list[ 1 : 3 ] # Slice的简写,与string相同,path="333",path[:3] list[: 3 ] # insert插入一个元素 list.insert( 2 , " 2.5 " ) # 扩展["1","2","3","4"] list.extend([ " 1 " , " 2 " , " 3 " , " 4 " ]) # 在list的搜索查询,index索引 list.index( " 1 " ) # 次换顺序 list.reverse() # 按照降序排序 list.sort() # 按照元素 [elem * 2 for elem in list] # 得到索引和所有值,params.items(), [ " %s=%s " % (keys, value) for keys, value in params.items()] # buildConnectionString 中的 list 解析 params = { " server " : " mpilgrim " , " database " : " master " , " uid " : " sa " , " pwd " : " secret " } # params.items()=[("server","mpilgrim"),("database","master"),("pwd","secret")] # [k for k, v in params.items()]等于params.keys # [v for k, v in params.items()]等于params.values # list 列表过滤方法 li = [ " a " , " mpilgrim " , " foo " , " b " , " c " , " b " , " d " , " d " ] [elem for elem in li if len(elem) > 1 ] # 筛选列表中数据长度大于一的数据 # 给列表中的每一个数值添加一个回车符 [elem + “ ” for elem in li if len(elem) > 1 ] # 过滤某个元素 [elem for elem in li if elem != " b " ] # 数据唯一 [elem for elem in li if elem == 1 ] # 使用filter方法过滤数据,filter(method_name,sequence) def f(x): return x % 2 != 0 and x % 3 != 0 if __name__ == " __main__ " : filter_list = filter(f,range( 2 , 25 )) print filter_list # map的用法 def f(x): return x * x * x if __name__ == " __main__ " : compute = map(f,range( 2 , 11 )) # 一个连接使用的例子: def f(x): return str(x) + " " if __name__ == " __main__ " : li = [ 1 , 2 , 3 , 4 , 5 , 6 ] compute = map(f,[elem for elem in li if elem != 1 ]) print compute # 启用多参数的compute def f(x,y): return x + y if __name__ == " __main__ " : seq = range( 8 ) compute = map(f,seq,seq) print compute # 一个求和的算法 def add(x,y): return x + y map(add,range( 1 , 11 )) reduce(add, range( 1 , 11 )) # 求和的最终算法,sum(range(1,11)) def sum(seq): def add(x,y): return x + y return reduce(add, seq, 0 def string_rfind(): path = " c:/test/dd.txt " print path[path.rfind( " / " ) + 1 :] def demand_method(): import class # 查询某个类的方法 help( class .method) # 查询某个类的方法的属性和方法 dir( class ) # 查询某个数组,元组,字符串的方法 dd = [] dd.method. __doc__ def Set_params(): # 一次性申明多个tuple v = ( ' 1 ' , ' 2 '' 3 ' ) (x,y,z) = v print x # x=1 print y # y=1 print z # z=1 def tuple_method(): tup = ( 2 , 4 , 6 , 8 , 10 ) # 替换 tup = ( 3 ,) + tup[ 1 :] # 元组转换为数组 tup = list(tup) # 数组转换为元组 tup = tuple(tup) # 由于元组不能使用tup[0]='3' list(tup),tup[0] = ' 3 ' ,tup = tuple(tup) def format_string(): a = " xin " b = " kai " print a + " is " + b print " %s is %s " % (a,b) # 格式化字符串与字符串连接符的比较 temp = 1 print " temp " + 1 # errors print " temp:%d " % (a) def split(): # 字典 params = { " server " : " mpilgrim " , " database " : " master " , " uid " : " sa " , " pwd " : " secret " } # 转成数组 list_params = [ " %s=%s " % (k,v) for k,v in params.items()] # 数组分割为字符串 string_params = " ; " .join(list_params) # 字符串分割为数组 list_1_params = string_params( " ; " ) list_1_params = string_params( " ; " ,count) def Choose_params(): # def info(object, spacing=10, collapse=1): info(odbchelper) info(odbchelper, 12 ) info(odbchelper, collapse = 0) info(spacing = 15 , object = odbchelper) def smba(): cd / etc / samba / def userpath(): import os import glob # C:Documents and SettingsAdministrator os.path.expanduser( " ~ " ) # C:Documents and SettingsAdministratorPython os.path.join(os.path.expanduser( " ~ " ), " Python " ) # ('C:/Documents and Settings/Administrator', 'Python') print os.path.split(os.path.join(os.path.expanduser( " ~ " ), " Python " )) # 便利一个path下的所有文件夹和路径 print os.listdir(os.path.expanduser( " ~ " )) # 如:便利path dirname = ' c:/ ' os.listdir(dirname) # 加载一个目录下所有的歌曲,完整的通配符.mp3 glob.glob( ' D:/MusicSources/Music1/*.mp3 ' ) # 加入s关键字的搜索 glob.glob( ' c:/music/_singles/s*.mp3 ' ) # 模糊查询 glob.glob( ' c:/music/*/s*.mp3 ' ) def getattr(): li = [ " Larry " , " Curly " ] getattr(li, " insert " )(0, 2 ) # li.insert(0,2) print li # getattr(object, method) def and_or(): # c,java中,bool ? a : b用法,延续到python中 bool and sequence_1 or sequence_2 # for example 1 and a or b return 如果a表达式为真,则返回a 0 and a or b return 如果a表达式为真,则返回b def find_linux_connections(): # 查看Linux系统某端口的连接数 netstat - a | grep 6669 | wc - l def tcpdump(): # 显示通过eth0接口上的所有报头 tcpdump - i eth0 # 过滤的是源主机为192.168.0.1与目的网络为192.168.0.0的报头,host主机,net(ack) 主机 tcpdump src host 192.168 . 0.1 and dst net 192.168 . 0.0 # 过滤源主机物理地址为XXX的报头 tcpdump ether src 00 : 50 : 04 :BA:9B and dst net (the other mac) # 过滤的是源主机为192.168.0.1与目的网络为192.168.0.0的报头,host主机,net(ack) 主机,端口为6669抱头 tcpdump src host 192.168 . 1.178 and net 192.168 . 0.202 and dst port 6669 # 过滤的是源主机为192.168.0.1的报头 tcpdump src host 192.168 . 0.202 def sys_path(): # 增加系统搜索路径 import sys sys.path.append( " $path " ) def zfile(): # 向数值的左侧填充0 a = 1 # 方法中包含向左侧添加0的个数 a.zfile( 5 ) def file(): # 文件权限模式 d = open($path,rights) # right模式,(r:只读模式;w:写出,同名文件覆盖模式;a:追加打开文件;r+:以读写方式打开文件) def shell(): # 把一个根目录下的所有文件拷贝到任意指定目录下 # 文件结构如下(/home/cqonline/test/test1 指定的任意目录 /user/lib) cd / home / cqonline # 如果文件相同则进行比较,不同则覆盖 cp . / test /* / usr / lib - f def file(): # 文件指针seek与tell的用法 path = open($path, ' r ' ) path.seek(offset,for_what) # offset:指针在该操作中从指定的引用位置移动offset 比特 # for_what:from_what值为0表示自文件起初处开始,1表示自当前文件指针位置开始,2表示自文件末尾开始。 # from_what可以忽略,其默认值为零,此时从文件头开始。 f = path.readline() f.tell() # 代表当前的指针的位置 # 返回一个整数:代表了文件对象在文件中的指针位置,该数值计量了从文件开头到指针处的比特数 def pickling(): # pickle模块,把任意的对象或者一段代码,封装为字符串。(关键字:封装与拆分) import pickle path = ($path, ' model ' ) pickle.dump(object,file - object) # object:需要封装的对象 # file-object:一个给定的文件对象 # 当文件被封装为一个对象,我们对这个封装的对象进行拆分 pickle.load(file - object) def exception(): # 异常文件以及try exception的用法 # 控制值输入类型的方法 while True: try : value = int(raw_input( " please input a int type's vlaue: " ) # 如果你输入的是其它类型的变量,系统会让你重新输入 print value except ValueError: # 指定错误类型,也可以except一个正常的运算进行调试 print " Oops! That was no valid number. Try again... " # 如果try中子句在运行中发生异常,则该句后所有的语句都不被执行,转入执行exception中的内容 # 一个try可以包含多个Exception的内容,来定义不同类型的错误,以此建立公用的错误类 except IOError, (errno, strerror): print " I/O error(%s): %s " % (errno, strerror) except ValueError: print " Could not convert data to an integer. " except : print " Unexpected error: " , sys.exc_info()[0] raise # 一个exception可以包含多个错误类型 except (RuntimeError, TypeError, NameError): pass # 一个文件操作类型异常错误机制 for arg in sys.argv[ 1 :]: try : f = open(arg, ’r’) except IOError: print ’cannot open’, arg else : print arg, ’has’, len(f.readlines()), ’lines’ f.close() # 使用else语句要比在try中增加附加代码要好,意外的截取那些不需要保护的代码,来进行调试 # 通过try返回异常程序的类型,再通过else方法输出发生异常时的状态类型,来确定发生异常的可能原因 # 这样既能保证程序的稳态,也对程序版本的信息安全进行了控制 # 不指定抛出类型,返回异常状态信息 except inst: print type(inst).args else : file = f.readlines() print file # 使用raise强制抛出异常信息,raise(第一个参数指定了所抛出异常的名称,第二个指定了异常的参数)