python学习代码
#!/bin/python#example 1.1
#applay
def function(a,b):
print(a,b)
def example1():
apply(function, ("whither","cannada?"))
apply(function, (1,2+3))
apply(function, (32,),{"b":"hello world"})
apply(function, (), {"a":"hello world","b":"new world, new way"})
class Rectangle:
def __init__(self, color="white", width=10, height=10):
print("create a", color, self, "sized", width, "x", height)
class RoundedRectangle(Rectangle):
def __init__(self, **kw):
apply(Rectangle.__init__, (self,), kw)
def example2():
rect = Rectangle(color="green", height=100, width=100)
rect = RoundedRectangle(color="blue", height=20,width=10)
def function2(**kwargs):
print(kwargs)
apply(function,(),kwargs)
def function3(*args):
print(args)
apply(function, args)
def example3():
function3(1,2)
function2(a="ddd",b=3)
#exmaple 4
def getfunctionbyname(module_name, function_name):
module = __import__(module_name)
return getattr(module, function_name)
def example4():
print(repr(getfunctionbyname("dumbdbm","open")))
#example 5
class LazyImport:
def __init__(self, module_name):
self.module_name = module_name
self.module = None
def __getattr__(self, item):
if self.module is None:
self.module = __import__(self.module_name)
return getattr(self.module, item)
def example5():
string = LazyImport("string")
print(string.lowercase)
print(string.module_name)
#example 6
def dump(value):
print(value,"=>",dir(value))
def example6():
import sys
dump(0)
dump(1.0)
dump(0.0j)
dump([])
dump({})
dump("string")
dump(len)
dump(sys)
#example 7
class A:
def a(self):
pass
def b(self):
pass
class B(A):
def c(self):
pass
def d(self):
pass
def getmembers(kclass, members=None):
#get a list of all class members, ordered by class
if members is None:
members=[]
for k in kclass.__bases__:
getmembers(k, members)
for m in dir(kclass):
if m not in members:
members.append(m)
return members
def example7():
print(getmembers(A))
print(getmembers(B))
print(getmembers(IOError))
#example 8
def example8():
book = "library2"
pages = 250
scripts = 350
print("the %(book)s book contains more than %(scripts)s scripts" % vars())
#example 9
def example9():
def dump(value):
print(type(value),value)
dump(1)
dump(1.0)
dump("one")
#example 10
def example10():
def load(file):
if isinstance(file, type("")):
file = open(file, "rb")
return file.read()
print(len(load("./__builtin__.py")),"bytes")
#print(len(load(open("./main.py","rb"))),"bytes")
#example 11
def example11():
def dump(function):
if callable(function):
print(function, "is callable")
else:
print(function, "is not callable")
class A:
def method(self,value):
return value
class B(A):
def __call__(self,value):
return value
a = A()
b = B()
dump(0) #simple object
dump("string")
dump(callable)
dump(dump)
dump(A)
dump(B)
dump(B.method)
dump(a)
dump(b)
dump(b.method)
#example 12
def example12():
class A:
pass
class B:
pass
class C(A):
pass
class D(A, B):
pass
def dump(object):
print(object,"=>",)
if isinstance(object, A):
print("A")
if isinstance(object, B):
print("B")
if isinstance(object, C):
print("C")
if isinstance(object, D):
print("D")
a = A()
b = B()
c = C()
d = D()
dump(a)
dump(b)
dump(c)
dump(d)
dump(0)
dump("string")
#example 13
def example13():
class A:
pass
class B:
pass
class C(A):
pass
class D(A, B):
pass
def dump(object):
print(object,"=>")
if issubclass(object, A):
print("A")
if issubclass(object, B):
print("B")
if issubclass(object, C):
print("C")
if issubclass(object, D):
print("D")
dump(A)
dump(B)
dump(C)
dump(D)
#dump(0)
#dump("string")
#example 14
def example14():
def dump(expression):
result = eval(expression)
print(expression, "=>", result, type(result))
dump("1")
dump("1.0")
dump("'string'")
dump("1.0+2.0")
dump("'*'*10")
dump("len('world')")
#example 15
def example15():
BODY = """print('the ant, an introduction')"""
code = compile(BODY, "<script>","exec")
print(locals())
print(code)
exec(code)
#example 16
#import sys,string
import string
class CodeGeneratorBackend:
"Simple code generator for Python"
def begin(self, tab ="\t"):
self.code = []
self.tab = tab
self.level = 0
def end(self):
self.code.append("")#make sure there's a newline at the end
return compile(string.join(self.code,"\n"),"<code>","exec")
def write(self,string):
self.code.append(self.tab * self.level + string)
def indent(self):
self.level = self.level + 1
def dedent(self):
if self.level == 0:
raise SystemError,"internal error in code generator"
self.level = self.level -1
def example16():
c = CodeGeneratorBackend()
c.begin()
c.write("for i in range(5):")
c.indent()
c.write("print('code generation made easy!')")
c.dedent()
exec(c.end())
#example 17
def example17():
def open(filename, mode="rb"):
import __builtin__
file = __builtin__.open(filename, mode)
if file.read(5) not in ("GIF87", "GIF89"):
print("hello world")
raise IOError, "not a GIF file"
file.seek(0)
return file
fp = open("__builtin__.py")
print(len(fp.read()),"bytes")
#example 18
class HTTPError(Exception):
def __init__(self, url, errcode, errmsg):
self.url = url
self.errcode = errcode
self.errmsg = errmsg
def __str__(self):
return ("<HTTPError for %s :%s %s> % (self.url, self.errcode, self.errmsg))")
def example18():
try:
raise HTTPError("http://www.python.org/foo", 200, "Not Found")
except HTTPError, error:
print("url =>",error.url)
print("errcode =>",error.errcode)
print("errmsg =>", error.errmsg)
#example 19
def example19():
import os , string
def replace(file, search_for, replace_with):
back = os.path.splitext(file)[0] + ".bak"
temp = os.path.splitext(file)[0] + ".tmp"
try:
os.remove(temp)
except os.error:
pass
fi = open(file)
fo = open(temp, "w")
for s in fi.readlines():
fo.write(string.replace(s, search_for, replace_with))
fi.close()
fo.close()
try:
os.remove(back)
except os.error:
pass
os.rename(file, back)
os.rename(temp, file)
print("replace string .")
#example 20
def example20():
import os
cwd = os.getcwd()
print(repr(cwd))
for file in os.listdir(cwd):
print(file)
pass
path = "C:\\"
os.chdir(path)
print(os.getcwd())
for file in os.listdir(path):
print(file)
#example 21
def example21():
import os ,time
currentPath = os.getcwd()
print(currentPath)
file = currentPath +"/__builtin__.py"
print("file is %s" % file)
def dump(st):
mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime = st
print("-size: %s bytes" % size)
print("-owner: %s %s" % (uid, gid))
print("-owner_s: %(hh)s %(uu)s" % {"hh":uid, "uu":gid})
print("-created:", time.ctime(ctime))
print("-last accessed:", time.ctime(atime))
print("-last modified:", time.ctime(mtime))
print("-mode:", oct(mode))
print("-inode/dev:", ino,dev)
st = os.stat(file)
print("stat")
print(st)
dump(st)
#example 22
def example22():
import os
if os.name == "nt":
command = "dir"
else:
command = "ls -l"
os.system(command)
#example 23
def example23():
import os, sys
program = "python"
currentPath = os.getcwd()
arguments = ["%s/main.py" % currentPath]
print(arguments)
result =os.execvp(program, (program,) + tuple(arguments))
print(result)
print("goodbye")
#example 24 without windows system!
#only for unix
def example24():
import os, sys
currentPath = os.getcwd()
scriptPath = "%s/main.py" % currentPath
def run(program, *args):
pid = os.fork()
if not pid:
os.execvp(program, (program,) + args)
return os.wait()[0]
run("python",scriptPath)
print("goodbye")
#example 25
#only for linux
import os, string
def run(program, *args):
#find executable
for path in string.split(os.environ["path"], os.pathsep):
print(path)
file = os.path.join(path, program) + ".exe"
try:
if os.path.exists(file):
return os.spawnv(os.P_WAIT, file, (file,)+args)
else:
raise os.error ,"the path is not exist"
except os.error,e:
print(e)
pass
raise os.error, "cannot find exectuable"
def example25():
run("python", "main.py")
#example 26
#only for windows
def example26():
import os, string
def run(program, *args, **kw):
mode = kw.get("mode", os.P_WAIT)
for path in string.split(os.environ["path"], os.pathsep):
file = os.path.join(path, program)+".exe"
try:
return os.spawnv(mode, file, (file,)+args)
except os.error:
pass
raise os.error, "cannot find excutable"
#exmaple 27
def example27():
import os, string
if os.name in ("nt", "dos"):
exefile = ".exe"
print("this os is windows or dos")
else:
exefile = ""
def spawn(program, *args):
try:
return os.spawnvp(program, (program,)+args)
except AttributeError:
pass
try:
spawnv = os.spawnv
except AttributeError:
#assume it's unix
pid = os.fork()
if not pid:
os.execvp(program, (program,)+args)
return os.wait()[0]
else:
#got sapwnv but no sapwnp: to look for an executable
for path in string.split(os.environ["PATH"], os.pathsep):
file = os.path.join(path, program) + exefile
if os.path.exists(file):
print("the file is %s" % file)
try:
return spawnv(os.P_WAIT, file , (file,)+args)
except os.error:
pass
else:
print("the file is no exist.")
raise IOError, "cannot find executable"
spawn("python", "main.py")
#example 28
#only for unix
def example28():
#daemon processes
import os, time
pid = os.fork()
if pid:
os._exit(0) #kill original
print("daemon started")
time.sleep(10)
print("daemon terminated")
#example 29
def example29():
import os, sys
try:
sys.exit(1)
except SystemExit, value:
print("caught exit(%s)" % value)
try:
print("try excute the code.")
os._exit(2)
except SystemExit, value:
print("caught exit(%s)" % value)
print("bye!")
#example 30
def example30():
import os
filename = "my/little/pony.txt"
#filename = "my/little/pony"
print("the filename:%s" % filename)
print("using %s ... " % os.name)
print("split =>", os.path.split(filename))
print("splitext =>", os.path.splitext(filename))
print("dirname =>", os.path.dirname(filename))
print("basename =>", os.path.basename(filename))
print("join =",os.path.join(os.path.dirname(filename), os.path.basename(filename)))
#example 31
def example31():
import os
FILES = (os.curdir, "/", "file", "/file", "samples", "samples/sample.jpg",
"directory/file", "../directory/file", "/directory/file"
)
for file in FILES:
print(file,"=>")
if os.path.exists(file):
print("EXISTS")
if os.path.isabs(file):
print("ISABS")
if os.path.isdir(file):
print("ISDIR")
if os.path.isfile(file):
print("ISFILE")
if os.path.islink(file):
print("ISLINK")
if os.path.ismount(file):
print("ISMOUNT")
print("######end######")
#exmaple 32
def example32():
import os
print(os.path.expanduser("~/.pythonrc"))
#example 33
def example33():
import os
for i in os.environ:
print(i)
os.environ["USER"] = "user"
print(os.path.expandvars("/home/$USER/config"))
print(os.path.expandvars("/$USER/folders"))
#example 34
def example34():
import os
def callback(arg, directory, files):
print("#######")
print(directory,"the files number is %d" % len(files))
for file in files:
print(os.path.join(directory, file), repr(arg))
os.path.walk(".", callback, "secret message")
#example 35
def example35():
import os
def index(directory):
# like os.listdir, but traverses directory trees
stack = [directory]
files = []
while stack:
directory = stack.pop()
for file in os.listdir(directory):
fullname = os.path.join(directory, file)
files.append(fullname)
if os.path.isdir(fullname) and not os.path.islink(fullname):
stack.append(fullname)
return files
for file in index("."):
print(file)
#example 36
def example36():
import os
class DirectoryWalker:
# a forward iterator that traverses a directory tree
def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0
def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not os.path.islink(fullname):
self.stack.append(fullname)
return fullname
for file in DirectoryWalker("."):
print(file)
#example 37
def example37():
import os , stat
class DirectoryStatWalker:
def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0
def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
fullname = os.path.join(self.directory, file)
st = os.stat(fullname)
mode = st[stat.ST_MODE]
if stat.S_ISDIR(mode) and not stat.S_ISLNK(mode):
self.stack.append(fullname)
return fullname,st
for file, st in DirectoryStatWalker("."):
print(file, st[stat.ST_SIZE])
#example 38
def example38():
import stat
import os, time
st = os.stat("./main.py")
print("mode => ", oct(stat.S_IMODE(st[stat.ST_MODE])))
print("type => ")
if stat.S_ISDIR(st[stat.ST_MODE]):
print("DIRECTORY")
if stat.S_ISREG(st[stat.ST_MODE]):
print("REGULAR")
if stat.S_ISLNK(st[stat.ST_MODE]):
print("LINK")
pass
print("size => ", st[stat.ST_SIZE])
print("last accessed => ", time.ctime(st[stat.ST_ATIME]))
print("last modified => ", time.ctime(st[stat.ST_MTIME]))
print("inode changed => ", time.ctime(st[stat.ST_CTIME]))
#example 39
def example39():
import string
text = "Monty Python's Flying Circus"
print("upper => %s" % string.upper(text))
print("lower => %s" % string.lower(text))
print("split => %s" % string.split(text))
print("join => %s" % string.join(text, '+'))
print("replace => %s" % string.replace(text, "Python", "Java"))
print("find => ", string.find(text, "Python"), string.find(text, "Java"))
print("count => ", string.count(text, 'n'))
#example 40
def example40():
text = "Monty Python's Flying Circus"
print("upper => %s" % text.upper())
print("lower => %s" % text.lower())
print("split => %s" % text.split())
print("join => %s" % text.join('+'))
print("replace => %s" % text.replace("Python", "Java"))
print("find => ", text.find("Python"), text.find("Java"))
print("count => ", text.count('n'))
#example 41
def example41():
import string
print(int("4711"))
print(string.atoi("4711"))
print(string.atoi("11147", 8)) #octal
print(string.atoi("1267", 16)) #hexadecimal
print(string.atoi("3mv", 36)) #whatever...
print(string.atoi("4711", 0))
print(string.atoi("04711", 0))
print(string.atoi("0x4711", 0))
print float("4711")
print(string.atof("1"))
print(string.atof("1.23e5"))
#example 42
def example42():
import re
text = "the Attila the Hun Show"
# a single character
m = re.match(".", text)
if m:
print(repr("."), "=>", repr(m.group(0)))
#any string fo characters
m = re.match(".*", text)
if m:
print(repr(".*"), "=>", repr(m.group(0)))
#a string of letters (at least one)
m = re.match("\w+", text)
if m:
print(repr("\w+"), "=>", repr(m.group(0)))
# a string of digits
m = re.match("\d+", text)
if m:
print(repr("\d+"), "=>", repr(m.group(0)))
#example 43
def example43():
import re
text = "10/15/99"
m = re.match("(\d{2})/(\d{2})/(\d{2,4})", text)
if m:
print(m.group(1, 2, 3))
print(m.group())
print(m.group(1))
print(len(m.group()))
#example 44
def example44():
import re
text = "Example 3: There is 1 date 10/25/95 in here!"
m = re.search("(\d{1,2})/(\d{1,2})/(\d{2,4})", text)
print(m.group(1), m.group(2), m.group(3), "group")
month, day, year = m.group(1, 2, 3)
print(month, day, year)
date = m.group(0)
print(date)
#example 45
def example45():
import re
text = "you're no fun anymore..."
#literal replace (string.replace is faster)
print(re.sub("fun", "entertaining", text))
#collapse all non-letter sequences to a single dash
print(re.sub("[^\w]+", "-", text))
#convert all words to beeps
print(re.sub("\S+", "-BEEP-", text))
#example 46
def example46():
import re, string
text = "a line of text\\012another line of text\\012etc..."
def octal(match):
#replace octal code with corresponding ASCII character
return chr(string.atoi(match.group(1), 8))
octal_pattern = re.compile(r"\\(\d\d\d)")
print(text)
print octal_pattern.sub(octal, text)
#example 47
def example47():
import re, string
def combined_pattern(patterns):
p = re.compile(string.join(map(lambda x: "("+x+")", patterns), "|"))
def fixup(v, m = p.match, r = range(0, len(patterns))):
try:
regs = m(v).regs
#print(regs)
except AttributeError:
return None # no match, so m.regs will fail
else:
for i in r:
if regs[i+1] != (-1, -1):
return i
return fixup
patterns = [r"\d+",
r"abc\d{2,4}",
r"p\w+"
]
p = combined_pattern(patterns)
print(p("129391"))
print(p("abc800"))
print(p("abc1600"))
print(p("python"))
print(p("perl"))
print(p("tcl"))
#example 48
def example48():
import math
print("e => ", math.e)
print("pi => ", math.pi)
print("hypot => ", math.hypot(3.0, 4.0))
#example 49
def example49():
import cmath
print("pi => ", cmath.pi)
print("sqrt(-1) => ", cmath.sqrt(-1))
#example 50
def example50():
import operator
sequence = 1, 2, 4
print("add => ", reduce(operator.add, sequence))
print("sub =>", reduce(operator.sub, sequence))
print("mul =>", reduce(operator.mul, sequence))
print("concat =>", operator.concat("spam", "egg"))
print("repeat =>", operator.repeat("spam", 5))
print("getitem =>", operator.getitem(sequence, 2))
print("indexOf =>", operator.indexOf(sequence, 2))
print("sequenceIncludes =>", operator.sequenceIncludes(sequence, 3))
#example 51
def example51():
import operator, UserList
def dump(data):
print(type(data), "=>")
if operator.isCallable(data):
print("CALLABLE")
if operator.isMappingType(data):
print("MAPPING")
if operator.isNumberType(data):
print("NUMBER")
if operator.isSequenceType(data):
print("SEQUENCE")
print("---")
dump(0)
dump("string")
dump("string"[0])
dump([1, 2, 3])
dump((1, 2, 3))
dump({"a": 1})
dump(len)
dump(UserList)
dump(UserList.UserList)
dump(UserList.UserList())
#example 52
def example52():
import copy
a = [[1], [2], [3]]
b = copy.copy(a)
print("before a=>", a)
print("before b=>", b)
if a is b:
print("a is b")
else:
print("a is not b")
#modify original
a[0][0] = 0
a[1] = None
if a[0][0] is b[0][0]:
print("a[0][0] is b[0][0]")
else:
print("a[0][0] is not b[0][0]")
print("after a=>", a)
print("after b=>", b)
#example 53:
def example53():
import copy
a = [[1], [2], [3]]
b = copy.deepcopy(a)
print("before a=>", a)
print("before b=>", b)
if a is b:
print("a is b")
else:
print("a is not b")
# modify original
a[0][0] = 0
a[1] = None
if a[0][0] is b[0][0]:
print("a[0][0] is b[0][0]")
else:
print("a[0][0] is not b[0][0]")
print("after a=>", a)
print("after b=>", b)
#example 54:
def example54():
import sys
print("script name is: ", sys.argv[0])
if len(sys.argv) > 1:
print("there are ", len(sys.argv) - 1, "arguments:")
for arg in sys.argv[1:]:
print(arg)
else:
print("there are no arguments!")
#example 55:
def example55():
import sys
print("path has", len(sys.path), "members")
#add the sample directory to the path
sys.path.insert(0, "samples")
import sample
sys.path = []
import random
#example 56:
def example56():
import sys
def dump(module):
print("module => ")
if module in sys.builtin_module_names:
print("<BUILTIN>")
else:
module = __import__(module)
print(module.__file__)
dump("os")
dump("sys")
dump("string")
dump("strop")
dump("zlib")
#example 57:
def example57():
import sys, pprint
moduleKeys = sys.modules.keys()
print(len(moduleKeys))
print(moduleKeys)
pprint.pprint(moduleKeys)
#example 58:
def example58():
import sys
variable = 1234
print(sys.getrefcount(0))
print(sys.getrefcount(variable))
print(sys.getrefcount(None))
#example 59:
def example59():
import sys
if sys.platform == "win32":
import ntpath
pathmodule = ntpath
elif sys.platform == "mac":
import macpath
pathmodule = macpath
else:
import posixpath
pathmodule = posixpath
print(pathmodule)
#example 60
def example60():
import sys
def test(n):
j = 0
for i in range(n):
j = j + 1
return n
def profiler(frame, event, arg):
print(event, frame.f_code.co_name, frame.f_lineno, "->", arg)
sys.setprofile(profiler)
test(1)
sys.setprofile(None)
test(2)
#example 61:
def example61():
import sys
def test(n):
j = 0
for i in range(n):
j = j + i
return n
def tracer(frame, event, arg):
print(event, frame.f_code.co_name, frame.f_lineno, "->", arg)
return tracer
sys.settrace(tracer)
test(1)
sys.settrace(None)
test(2)
#example 62:
def example62():
import sys, string
class Redirect:
def __init__(self, stdout):
self.stdout = stdout
def write(self, s):
self.stdout.write(string.lower(s))
old_stdout = sys.stdout
sys.stdout = Redirect(sys.stdout)
print("HEJA SVERIGE")
print("FRISKT HUM\303\226R")
sys.stdout = old_stdout
print("M\303\205\303\205\303\205\303\205L!")
#example 63:
def example63():
import sys
print("hello")
sys.exit(1)
print("there")
#example 64:
def example64():
import sys
print("hello")
try:
sys.exit(1)
except SystemExit, e:
pass
print("get the except:SystemExit %s" % e)
print("there")
#example 65:
def example65():
import sys
def exitfunc():
print("world")
sys.exitfunc = exitfunc
print("hello ")
sys.exit(1)
print("there")
#example 66:
def example66():
import atexit
def exit(*args):
print("exit", args)
#register two exit handler
atexit.register(exit)
atexit.register(exit, 1)
atexit.register(exit, "hello", "world", "!")
#example 67:
def example67():
import time
now = time.time()
print(now, "Seconds since ", time.gmtime(0)[:6])
print("-local time:", time.localtime(now))
print("-utc:", time.gmtime(now))
#example 68:
def example68():
import time
now = time.localtime(time.time())
print(time.asctime(now))
print(time.strftime("%y/%m/%d %H:%M", now))
print(time.strftime("%c", now))
print(time.strftime("%I %p", now))
print(time.strftime("%Y-%m-%d %H:%M:%S %Z", now))
year, month, day, hour, minute, second, weekday, yearday, daylight = now
print("%04d-%02d-%02d" % (year, month, day))
print("%02d:%02d:02%d" % (hour, minute, second))
print(("MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN")[weekday], yearday)
#example 69
def example69():
import time
try:
strptime = time.strptime
except AttributeError:
print("exception about the function: strptime")
from _strptime import strptime
print(strptime("31 Nov 00"), "%d %b %y")
#example 70
def example70():
import time
t0 = time.time()
tm = time.localtime(t0)
print(tm)
print(t0)
print(time.mktime(tm))
#example 71
def example71():
import time
def procedure():
time.sleep(2.5)
#measure process time
t0 = time.clock()
procedure()
print(time.clock() - t0, "Seconds process time")
#measure wall time
t0 = time.time()
procedure()
print(time.time() - t0, "Seconds wall time")
if __name__ == "__main__":
print("process %s section start" % "__builtin__")
print("---")
boolWhichWay = True
if boolWhichWay:
for i in xrange(1, 1000):
strFunctionName = "example%d" % i
if strFunctionName in globals():
pass
else:
strFunctionName = "example%d" % (i-1)
strExcuteFunctionName = "%s()" % strFunctionName
print("#excute function %s:" % strFunctionName)
eval(str(strExcuteFunctionName), globals())
print("---")
break
else:
for i in xrange(1, 1000):
strFunctionName = "example%d" % i
if strFunctionName in globals():
strFunctionName = "example%d" % i
strExcuteFunctionName = "%s()" % strFunctionName
print("#excute function %s:" % strFunctionName)
eval(str(strExcuteFunctionName), globals())
print("---")
else:
break
print("process end")
以上是 python学习代码 的全部内容, 来源链接: utcz.com/z/387818.html