Standard Library Modules Using Notes

  • 类型转换

int(x [,base ]) 整数 long(x [,base ]) 长整数 float(x ) 浮点数 complex(real [,imag ]) 复数 str(x ) 字符串 repr(x ) 表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 元组 list(s ) 列表 chr(x ) 字符 unichr(x ) Unicode字符 ord(x )字符转换为它的整数值
hex(x ) 整数转换为一个十六进制字符串 oct(x ) 整数转换为一个八进制字符串

  • _winreg
REG_NONE 0 REG_SZ 1 REG_EXPAND_SZ 2 REG_BINARY 3 REG_DWORD 4 REG_DWORD_LITTLE_ENDIAN 4 REG_DWORD_BIG_ENDIAN 5 REG_LINK 6 REG_MULTI_SZ 7
REG_RESOURCE_LIST 8 REG_FULL_RESOURCE_DESCRIPTOR 9 REG_RESOURCE_REQUIREMENTS_LIST 10 REG_QWORD 11 REG_QWORD_LITTLE_ENDIAN 12

CloseKey() – 关闭一个Key
ConnectRegistry() – 链接到其他机器的注册表
CreateKey() – 创建一个Key
DeleteKey() – 删除一个Key
DeleteValue() – 删除一个Key里面的值(value)
EnumKey() – 为已经打开的Key里面的子键建立索引
EnumValue() – 为打开的键中的值建立索引
FlushKey() – 回写所有的键属性改变到注册表
LoadKey() – 从指定文件读入键信息
OpenKey() – 打开一个键
OpenKeyEx()
QueryValue() – 在注册表中检索一个键的路径
QueryValueEx() – 注册表中检索一个键的路径
QueryInfoKey() – 返回关于键的信息
SaveKey() – 保存键到文件
SetValue() – 设置一个键
SetValueEx() – 设置一个值
# traverse all values of one key
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", 
              0, _winreg.KEY_WRITE)
try:
    i = 0
    while True:
        name, value, type = _winreg.EnumValue(key, i)
        print repr(name), value, type
        i += 1
except WindowsError, e:
    print e

# query specified value directly
(value, valuetype) = _winreg.QueryValueEx(key, 'Path')
View Code
 1 # __author__ = 'rtian'
 2 import sys, os
 3 
 4 # 返回path规范化的绝对路径
 5 os.path.abspath('../csv\\test.csv') # 'C:\\csv\\test.csv' 
 6 
 7 # 将path分割成目录和文件名二元组返回
 8 os.path.split('c:\\csv\\test.csv') # ('c:\\csv', 'test.csv') 
 9 os.path.split('c:\\csv\\') # ('c:\\csv', '') 
10 
11 # 返回path最后的文件名,即os.path.split(path)的第二个元素
12 os.path.basename('c:\\test.csv') # 'test.csv' 
13 os.path.basename('c:\\csv') # 'csv'(这里csv被当作文件名处理了)   
14 os.path.basename('c:\\csv\\') # ''
15 
16 # 返回list中,所有path共有的最长的路径
17 os.path.commonprefix(['/home/td', '/home/td/ff', '/home/td/fff']) # '/home/td' 
18 
19 # 如果path存在,返回True;如果path不存在,返回False
20 os.path.exists('c:\\') # True   
21 
22 # 如果path是绝对路径,返回True
23 os.path.isabs('path')
24 
25 # 如果path是一个存在的文件,返回True。否则返回False 
26 os.path.isfile('c:\\boot.ini') # True   
27 os.path.isfile('c:\\csv\\') # False   
28 
29 # 如果path是一个存在的目录,则返回True。否则返回False
30 os.path.isdir('c:\\windows\\test.csv') # False
31 
32 # 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
33 os.path.join('c:\\', 'csv', 'test.csv') # 'c:\\csv\\test.csv'   
34 os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv') # 'c:\\csv\\test.csv'   
35 os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c') # '/home/aa/bb/c'   
36 
37 # 在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为饭斜杠
38 os.path.normcase('c:/windows\\system32\\') # 'c:\\windows\\system32\\'
39 
40 # 规范化路径
41 os.path.normpath('c://windows\\System32\\../Temp/') # 'c:\\windows\\Temp'
42 
43 #从start开始计算相对路径
44 os.path.relpath(path[, start])
45 p = 'a/b/c/d'
46 print os.path.relpath(p) #默认当前目录开始 相当于 ./a/b/c/d
47 print os.path.relpath(p,'a/b')# 以a/b/目录开始 c/d
48 
49 # 返回(drivername,fpath)元组
50 os.path.splitdrive('c:\\windows') # ('c:', '\\windows')   
51 
52 # 分离文件名与扩展名;默认返回(fname,fextension)元组,可做分片操作
53 os.path.splitext('c:\\csv\\test.csv') # ('c:\\csv\\test', '.csv')
54 
55 # 返回path的文件的大小(字节)
56 os.path.getsize('c:\\boot.ini')# 3.299L
57 
58 # 返回path所指向的文件或者目录的最后存取时间a 最后修改时间m
59 os.path.getatime('path')
60 os.path.getmtime('path')
61 
62 # 获取操作系统当前的路径
63 os.getcwd()
64 os.path.abspath(os.curdir)
65 os.path.abspath('.')
66 
67 os.path.dirname(__file__)
68 # (1).当"print os.path.dirname(__file__)"所在脚本是以完整路径被运行的, 那么将输出该脚本所在的完整路径,比如:
69 # python d:\pythonSrc\test\test.py 那么将输出 d:\pythonSrc\test
70 # (2).当"print os.path.dirname(__file__)"所在脚本是以相对路径被运行的, 那么将输出空目录,比如:
71 # python test.py 那么将输出空字符串
View Code
import re

# re.match 尝试从字符串的开始匹配一个模式, 匹配成功,则返回一个Match,否则返回None
re.match(pattern, string, flags)
re.match(‘super’, ‘superstition’).span() (0, 5)

# re.search函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回,如果字符串没有匹配,则返回None
re.search(pattern, string, flags)

# re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ' ' 替换成 '-' 
>>> text = "hell o , you asr.."
>>> re.sub(r"\s+", '-', text) 'hell-o-,-you-asr..'
re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);# 将字符串中的空格' '替换为'[ ]'。

# re.split来分割字符串, 将字符串按空格分割成一个单词列表
>>> re.split(r'\s+', text) ['hell', 'o', ',', 'you', 'asr..']

# re.findall获取字符串中所有匹配的字符串
re.findall(r'\w*oo\w*', text)获取字符串中,包含'oo'的所有单词

# re.compile把经常使用的正则表达式编译成正则表达式对象
text = "JGood is a handsome boy, he is cool, clever, and so on..."
regex = re.compile(r'\w*oo\w*')
print regex.findall(text)   #查找所有包含'oo'的单词
print regex.sub(lambda m: '[' + m.group(0) + ']', text) #将字符串中含有'oo'的单词用[]括起来。
View Code
  • subprocess 
import subprocess
cmd="cmd.exe"
begin=1
end=3
while begin<end:
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                   stdin=subprocess.PIPE,
                   stderr=subprocess.PIPE)
    p.stdin.write("ping 192.168.32."+str(begin)+"\n")
    p.stdin.close()
    p.communicate()
    print "execution result: %s"%p.stdout.read()
    begin=begin+1
View Code
  • shutil 
import os
import shutil

# 用shutil.copytree当dst存在且不能删除时
root_src_dir = 'Src Directory\\'
root_dst_dir = 'Dst Directory\\'

for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir)
    if not os.path.exists(dst_dir):
        os.mkdir(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.move(src_file, dst_dir)
View Code
  • __all__
一、在模块(*.py)中使用意为导出__all__列表里的类、函数、变量等成员,否则将导出modualA中所有不以下划线开头(私有)的成员,在模块中使用__all__属性可避免在相互引用时的命名冲突
二、在包(假设pkgA,pkgA是一个文件夹)的__init__.py中意为导出包里的模块
例:pkgA/__init__.py
__all__=["modualA","modualB"]
from modualA import class1,class2
from modualB import fun1,class3

使用:from pkgA import *
以上语句即执行了pkgA下的__init__.py,导入两个模块,和这两模块下的函数和类
View Code
  • sys 
# The content of file F:\test\test.py as follows:
import sys
print sys.argv
print sys.path[0]

# Run it in different path
C:\ > python F:\test\test.py
['F:\test\test.py']
['F:\test\test.py']

F:\ > python test\test.py
['test\test.py']
['F:\test\test.py']

# So, argv[0] is the same as the first arg of command totally, on matter relative or absolute path
# but path[0] will fill the relative path to absolute one
View Code

    *  Get absolute path of script: os.path.split(os.path.realpath(__file__))[0]

posted @ 2015-10-15 17:30  irun  阅读(237)  评论(0编辑  收藏  举报