diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ddc0717 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +#windows +*.bak \ No newline at end of file diff --git a/datastruct/binarysearch.py b/datastruct/binarysearch.py index fa6a1e2..cc7c316 100644 --- a/datastruct/binarysearch.py +++ b/datastruct/binarysearch.py @@ -10,16 +10,16 @@ def BinarySearch(l,key): elif (l[mid] > key): high = mid -1 else: - print "use %d times" % i + print(("use %d times" % i)) return mid return -1 if __name__ == "__main__": l=[1,4,5,6,7,8,9,44,333,2233] - print l - print BinarySearch(l,4) - print BinarySearch(l,44) - print BinarySearch(l,8) - print BinarySearch(l,2233) - print BinarySearch(l,77) + print(l) + print((BinarySearch(l,4))) + print((BinarySearch(l,44))) + print((BinarySearch(l,8))) + print((BinarySearch(l,2233))) + print((BinarySearch(l,77))) diff --git a/datastruct/btree.py b/datastruct/btree.py index 69434e8..a9f53eb 100644 --- a/datastruct/btree.py +++ b/datastruct/btree.py @@ -13,7 +13,7 @@ def insertRight(self,value): return self.right def show(self): - print self.data + print(self.data) def preorder(node): if node.data: @@ -50,13 +50,13 @@ def postorder(node): B=Root.insertRight("B") E=B.insertRight("E") - print "pre-traversal" + print("pre-traversal") preorder(Root) - print "in-traversal" + print("in-traversal") inorder(Root) - print "post-traversal" + print("post-traversal") postorder(Root) diff --git a/datastruct/graph.py b/datastruct/graph.py index 834670b..158e0d3 100644 --- a/datastruct/graph.py +++ b/datastruct/graph.py @@ -25,11 +25,11 @@ def generatePath(graph,path,end,results): 'G':['E'] } r = searchGraph(Graph,'A','D') - print "A to D" + print("A to D") for i in r: - print i + print(i) r=searchGraph(Graph,'A','E') - print "A to E" + print("A to E") for i in r: - print i + print(i) diff --git a/datastruct/queue.py b/datastruct/queue.py index 64da3e4..ffb1579 100644 --- a/datastruct/queue.py +++ b/datastruct/queue.py @@ -35,9 +35,9 @@ def empty(self): queue=Queue() for i in range(10): queue.In(i) - print queue.End() + print(queue.End()) for i in range(10): - print queue.Out() + print(queue.Out()) diff --git a/datastruct/sort.py b/datastruct/sort.py index b190701..e880523 100644 --- a/datastruct/sort.py +++ b/datastruct/sort.py @@ -13,7 +13,7 @@ def insertRight(self,value): return self.right def show(self): - print self.data + print(self.data) def inorder(node): if node.data: @@ -53,9 +53,9 @@ def insert(node,value): for i in range(1,len(l)): insert(Root,l[i]) - print "1---->10" + print("1---->10") inorder(Root) - print "10--->1" + print("10--->1") rinorder(Root) diff --git a/datastruct/stack.py b/datastruct/stack.py index e5b65ce..fbceacd 100644 --- a/datastruct/stack.py +++ b/datastruct/stack.py @@ -48,12 +48,12 @@ def isFull(self): for i in range(10): stack.push(i) - print stack.Top() + print(stack.Top()) for i in range(10): - print stack.pop() + print(stack.pop()) stack.empty() - print stack.Top() + print(stack.Top()) diff --git a/expand/1.py b/expand/1.py index 3239a25..665bf28 100644 --- a/expand/1.py +++ b/expand/1.py @@ -12,15 +12,15 @@ def printNum(): - sInput = raw_input(u"请输入你猜的数字(1-100):") + sInput = input("请输入你猜的数字(1-100):") try: nInput = int(sInput) - except (ValueError,TypeError),diag: - print str(diag) + except (ValueError,TypeError) as diag: + print(str(diag)) if(nInput < 1 or nInput > 100): - print u"你数字不在范围之内,请重新输入" + print("你数字不在范围之内,请重新输入") return nInput @@ -33,21 +33,21 @@ def main(): while(nValue!= nInput): if (nValue > nInput): - print u"你猜的数小了" + print("你猜的数小了") elif (nValue < nInput): - print u"你猜的数大了" + print("你猜的数大了") nTotal += 1 nInput=printNum() - print u"恭喜你猜对了" - print u"你直到猜对 共猜了%d次" % nTotal + print("恭喜你猜对了") + print("你直到猜对 共猜了%d次" % nTotal) if nTotal < 10: - print u"恭喜,你的成绩超过了平均水平" + print("恭喜,你的成绩超过了平均水平") else: - print u"很遗憾,你成绩没达到平均水平" + print("很遗憾,你成绩没达到平均水平") if __name__ == "__main__": diff --git a/expand/2.py b/expand/2.py index 8f1d16f..de8be9e 100644 --- a/expand/2.py +++ b/expand/2.py @@ -17,9 +17,9 @@ def printReplace_re(srcStr,word): return srcStr def main(): - srcStr = raw_input(u"请输入一个字符串:") + srcStr = input("请输入一个字符串:") destStr=printReplace_re(srcStr,'i') - print destStr + print(destStr) if __name__ == "__main__": diff --git a/primer/10/card.py b/primer/10/card.py index e6bac33..5b33fab 100644 --- a/primer/10/card.py +++ b/primer/10/card.py @@ -1,7 +1,7 @@ def safe_float(obj): try: retval = float(obj) - except (ValueError,TypeError),diag: + except (ValueError,TypeError) as diag: retval = str(diag) return retval @@ -9,7 +9,7 @@ def main(): log = open("cardlog.txt","w") try: ccfile = open("carddata.txt","r") - except IOError,e: + except IOError as e: log.write("no txns this \n") log.close() return @@ -25,9 +25,9 @@ def main(): log.write("data ....processed\n") else: log.write("ignored: %s" % result) - print "$%.2f (new balance)" % (total) + print("$%.2f (new balance)" % (total)) log.close() if __name__ == '__main__': - print "run" + print("run") main() diff --git a/primer/10/myexc.py b/primer/10/myexc.py index 0e3245f..769546d 100644 --- a/primer/10/myexc.py +++ b/primer/10/myexc.py @@ -24,7 +24,7 @@ def fileAargs(file,mode,agrs): 'access' in dir(os): perms = '' perms = {'r':os.R_OK,'w':os.W_OK,'x':os.X_OK} - pkeys = permd.keys() + pkeys = list(permd.keys()) pkeys.sort() pkeys.reverse() @@ -51,18 +51,17 @@ def fileAargs(file,mode,agrs): def myconnnect(sock,host,port): try: sock.connect((hosy,port)) - except socket.error,args: + except socket.error as args: myargs = updArgs(args) if len(myargs) == 1: myargs = (errno.ENXIO,myargs[0]) - raise NetworkError,\ - updArgs(myargs,host +":" + str(port)) + raise NetworkError(updArgs(myargs,host +":" + str(port))) def myopen(file,mode ="r"): try: fo = open(file,mode) - except IOError,args: - raise FileError,fileArgs(file,mode,args) + except IOError as args: + raise FileError(fileArgs(file,mode,args)) return fo def testfile(): @@ -70,28 +69,28 @@ def testfile(): f = open(file,"w") f.close() - for eachTest in ((0,"r"),(0100,"r"), \ - (0400,"w"),(0500,"w")): + for eachTest in ((0,"r"),(0o100,"r"), \ + (0o400,"w"),(0o500,"w")): try: os.chmod(file,eachTest[0]) f=myopen(file,eachTest[1]) - except FileError,args: - print "%s: %s" % \ - (args.__class__.__name__,args) + except FileError as args: + print("%s: %s" % \ + (args.__class__.__name__,args)) else: - print file,"open ok..perm ignored" + print(file,"open ok..perm ignored") f.close() - os.chmod(file,0777) + os.chmod(file,0o777) os.unlink(file) def testnet(): s = socket.socket(socket.AF_INET.socket.SOCK_STREAM) for eachHost in ("deli","www"): try: myconnect(s,"deli",8080) - except NetworkError,args: - print "%s:%s" %\ - (args.__class__.__name__,args) + except NetworkError as args: + print("%s:%s" %\ + (args.__class__.__name__,args)) if __name__ == "__main__": testfile() testnet() diff --git a/primer/11/Gui.py b/primer/11/Gui.py index 6bff1f6..e2e2e5d 100644 --- a/primer/11/Gui.py +++ b/primer/11/Gui.py @@ -1,9 +1,9 @@ from functools import partial -import Tkinter +import tkinter -root=Tkinter.Tk() -MyButton = partial(Tkinter.Button,root, +root=tkinter.Tk() +MyButton = partial(tkinter.Button,root, fg="white",bg="blue") b1= MyButton(text="button 1") b2=MyButton(text="button 2") diff --git a/primer/11/deco.py b/primer/11/deco.py index 21d7389..735438b 100644 --- a/primer/11/deco.py +++ b/primer/11/deco.py @@ -3,8 +3,8 @@ def tsfunc(func): def wrappedFunc(): - print "[%s] %s() called" % \ - (ctime(),func.__name__) + print("[%s] %s() called" % \ + (ctime(),func.__name__)) return func() return wrappendFunc diff --git a/primer/11/easyMath.py b/primer/11/easyMath.py index e14d53b..9b88bfa 100644 --- a/primer/11/easyMath.py +++ b/primer/11/easyMath.py @@ -14,22 +14,22 @@ def doprob(): oops =0 while True: try: - if int(raw_input(pr)) == ans: - print "corrent" + if int(input(pr)) == ans: + print("corrent") break if oops == MAXTRIES: - print "answer \n %s%d" %(pr,ans) + print("answer \n %s%d" %(pr,ans)) else: - print "incorrent...try again" + print("incorrent...try again") oops += 1 except (KeyboardInterrupt, EOFError,ValueError): - print "invalid input ... try again" + print("invalid input ... try again") def main(): while True: doprob() try: - opt= raw_input("Again?[y]".lower()) + opt= input("Again?[y]".lower()) if opt and opt[0] == "n": break except (KeyboardInterrupt,EOFError): diff --git a/primer/11/grabWeb.py b/primer/11/grabWeb.py index 5b3de06..c952601 100644 --- a/primer/11/grabWeb.py +++ b/primer/11/grabWeb.py @@ -1,5 +1,5 @@ -from urllib import urlretrieve +from urllib.request import urlretrieve def firstNoBlank(lines): for eachLine in lines: @@ -12,8 +12,8 @@ def firstLast(webpage): f = open(webpage) lines= f.readlines() f.close() - print firstNoBlank(lines),lines.reverse() - print firstNoBlank(lines), + print(firstNoBlank(lines),lines.reverse()) + print(firstNoBlank(lines), end=' ') def download(url = "http://www.cqupt.edu.cn",process=firstLast): try: diff --git a/primer/11/numconv.py b/primer/11/numconv.py index 63eb282..68c3232 100644 --- a/primer/11/numconv.py +++ b/primer/11/numconv.py @@ -2,7 +2,7 @@ def convert(func,seq): return[func (eachNum ) for eachNum in seq] -myseq=(123,45.67,-6.2e8,99999999L) -print convert(int,myseq) -print convert(long,myseq) -print convert(float,myseq) +myseq=(123,45.67,-6.2e8,99999999) +print(convert(int,myseq)) +print(convert(int,myseq)) +print(convert(float,myseq)) diff --git a/primer/11/odd.py b/primer/11/odd.py index 2a37d6a..4e94d99 100644 --- a/primer/11/odd.py +++ b/primer/11/odd.py @@ -7,4 +7,4 @@ allNums =[] for eachNum in range(9): allNums.append(randint(1,99)) -print[n for n in allNums if n%2] +print([n for n in allNums if n%2]) diff --git a/primer/11/testit.py b/primer/11/testit.py index ad5037e..6ab05dd 100644 --- a/primer/11/testit.py +++ b/primer/11/testit.py @@ -3,24 +3,24 @@ def testit(func,*nkwargs,**kwargs): try: retval = func(*nkwargs,**kwargs) result = (True,retval) - except Exception,diag: + except Exception as diag: result = (False,str(diag)) return result def test(): - funcs =(int,long,float) + funcs =(int,int,float) vals = (1234,12.34,"1234","12.34") for eachFunc in funcs: - print "_"*20 + print("_"*20) for eachVal in vals: retval = testit(eachFunc,eachVal) if retval[0]: - print "%s(%s)=" % \ - (eachFunc.__name__,"eachVal"),retval[1] + print("%s(%s)=" % \ + (eachFunc.__name__,"eachVal"),retval[1]) else: - print "%s(%s)=FAILED:" %\ - (eachFunc.__name__,"eachVal"),retval[1] + print("%s(%s)=FAILED:" %\ + (eachFunc.__name__,"eachVal"),retval[1]) if __name__ == "__main__": test() diff --git a/primer/13/NumStr.py b/primer/13/NumStr.py index 986062b..ccb8b4e 100644 --- a/primer/13/NumStr.py +++ b/primer/13/NumStr.py @@ -17,8 +17,8 @@ def __mul__(self,num): if isinstance(num,int): return self.__class__(self.__num *num,self.__string *num) else: - raise TypeError,"__num__ error" - def __nonzero__(self): + raise TypeError("__num__ error") + def __bool__(self): return self.__num or len(self.__string) def __norm_cval(self,cmpres): return cmp(cmpres,0) diff --git a/primer/13/Rand.py b/primer/13/Rand.py index 1b56d0d..f67eb47 100644 --- a/primer/13/Rand.py +++ b/primer/13/Rand.py @@ -6,5 +6,5 @@ def _init_(self,seq): self.data = seq def _iter_(self): return self - def next(self): + def __next__(self): return choice(self.data) diff --git a/primer/13/file.py b/primer/13/file.py index 8830909..ebcc5c8 100644 --- a/primer/13/file.py +++ b/primer/13/file.py @@ -7,22 +7,22 @@ def __init__(self,name=None): self.name = name def __get__(self,obj,typ=None): if self.name not in File.saved: - raise AttributeError,"%r used before assignment " % self.name + raise AttributeError("%r used before assignment " % self.name) try: f = open(self.name,"r") val = pickle.load(f) f.close() return val except (pickle.UnpicklingError,IOError,EOFError,AttributeError,\ - ImportError,IndexError),e: - raise AttributeError,"could not read %r:%s" % (self.name,e) + ImportError,IndexError) as e: + raise AttributeError("could not read %r:%s" % (self.name,e)) def __set__(self,obj,val): f = open(self.name,"w") try: pickle.dump(val,f) File.saved.append(self.name) - except (TypeError,pickle.PicklingError),e: - raise AttributeError,"could not pickle %r " % self.name + except (TypeError,pickle.PicklingError) as e: + raise AttributeError("could not pickle %r " % self.name) finally: f.close() @@ -30,5 +30,5 @@ def __delete__(self,obj): try: os.unlink(self.name) File.saved.remove(self.name) - except (OSError,ValueError),e: + except (OSError,ValueError) as e: pass diff --git a/primer/13/meta.py b/primer/13/meta.py index 243a253..f381e47 100644 --- a/primer/13/meta.py +++ b/primer/13/meta.py @@ -7,22 +7,18 @@ def __init__(cls,name,bases,attrd): raise TypeError("class overring __str__") if "__repr__" not in attrd: warn("class suggests __repr__",stacklevel = 3) -print "define ReqStr (meta)class \n" - -class Foo(object): - __metaclass__ = ReqStr +print("define ReqStr (meta)class \n") +class Foo(object, metaclass=ReqStr): def __str__(self): return "instance of class",self.__class__.__name__ -print "defined Foo class\n" - -class Bar(object): - __metaclass__ = ReqStr +print("defined Foo class\n") +class Bar(object, metaclass=ReqStr): def __str__(self): return self.__class__.__name__ -print "defined Bar class\n " +print("defined Bar class\n ") -class FooBar(object): - __metaclass__ = ReqStr -print "defined FooBar class \n" +class FooBar(object, metaclass=ReqStr): + pass +print("defined FooBar class \n") diff --git a/primer/13/time.py b/primer/13/time.py index de514b5..c2812a6 100644 --- a/primer/13/time.py +++ b/primer/13/time.py @@ -10,7 +10,7 @@ def get(self): return self.__data def gettimeval(self,t_type): if not isinstance(t_type,str) or t_type[0] not in "cma": - raise TypeError," arg c m a" + raise TypeError(" arg c m a") return getattr(self,"_%s__%stime" % (self.__class__.__name__,t_type[0])) def gettimestr(self,t_type): return ctime(self.gettimeval(t_type)) diff --git a/primer/16/sockCli.py b/primer/16/sockCli.py index f97acee..8120ebe 100644 --- a/primer/16/sockCli.py +++ b/primer/16/sockCli.py @@ -8,7 +8,7 @@ while True: tcpCliSock = socket(AF_INET,SOCK_STREAM) tcpCliSock.connect(ADDR) - data=raw_input(">") + data=input(">") if not data: break @@ -16,5 +16,5 @@ data = tcpCliSock.recv(BUFSIZ) if not data: break - print data.strip() + print(data.strip()) tcpCliSock.close() diff --git a/primer/16/sockServ.py b/primer/16/sockServ.py index 9e4e38f..9fdc137 100644 --- a/primer/16/sockServ.py +++ b/primer/16/sockServ.py @@ -1,4 +1,4 @@ -from SocketServer import (TCPServer as TCP, +from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH) from time import ctime @@ -8,10 +8,10 @@ class MyRequestHandler(SRH): def handle(self): - print "......connected from :",self.client_address + print("......connected from :",self.client_address) self.wfile.write('[%s] %s' % (ctime(),self.rfile.readline())) tcpSer = TCP(ADDR,MyRequestHandler) -print "waiting for connection..." +print("waiting for connection...") tcpSer.serve_forever() diff --git a/primer/16/tcpclient.py b/primer/16/tcpclient.py index b346fc6..cc22115 100644 --- a/primer/16/tcpclient.py +++ b/primer/16/tcpclient.py @@ -9,13 +9,13 @@ tcpCliSock.connect(ADDR) while True: - data = raw_input(">") + data = input(">") if not data: break tcpCliSock.send(data) data = tcpCliSock.recv(BUFSIZ) if not data: break - print data + print(data) tcpCliSock.close() diff --git a/primer/16/tcpserver.py b/primer/16/tcpserver.py index 688b0aa..42b8916 100644 --- a/primer/16/tcpserver.py +++ b/primer/16/tcpserver.py @@ -12,9 +12,9 @@ tcpSerSock.listen(5) while True: - print "waiting from connection..." + print("waiting from connection...") tcpCliSock,addr = tcpSerSock.accept() - print "...connected from :",addr + print("...connected from :",addr) while True: data = tcpCliSock.recv(BUFSIZ) diff --git a/primer/16/udpCli.py b/primer/16/udpCli.py index 9a502f3..8a08182 100644 --- a/primer/16/udpCli.py +++ b/primer/16/udpCli.py @@ -8,12 +8,12 @@ udpCliSock= socket(AF_INET,SOCK_DGRAM) while True: - data = raw_input(">") + data = input(">") if not data: break udpCliSock.sendto(data,ADDR) data,ADDR= udpCliSock.recvfrom(BUFSIZ) if not data: break - print data + print(data) udpCliSock.close() diff --git a/primer/16/udpSer.py b/primer/16/udpSer.py index bf7eabb..70f293d 100644 --- a/primer/16/udpSer.py +++ b/primer/16/udpSer.py @@ -10,8 +10,8 @@ udpSerSock.bind(ADDR) while True: - print "waiting for message..." + print("waiting for message...") data,addr = udpSerSock.recvfrom(BUFSIZ) udpSerSock.sendto('[%s] %s' %(ctime(),data),addr) - print "...received from and returned to :",addr + print("...received from and returned to :",addr) udpSerSock.close() diff --git a/primer/18/sleep.py b/primer/18/sleep.py index 65c80cd..c204a19 100644 --- a/primer/18/sleep.py +++ b/primer/18/sleep.py @@ -1,26 +1,26 @@ from time import sleep,ctime -import thread +import _thread loops =[4,2,11] def loop(nloop,nsec,lock): - print " start loop:",nloop,"at",ctime() + print(" start loop:",nloop,"at",ctime()) sleep(nsec) - print "loop :",nloop, "done at:",ctime() + print("loop :",nloop, "done at:",ctime()) def main(): - print "start at:", ctime() + print("start at:", ctime()) locks = [] - nloops = range(len(loops)) + nloops = list(range(len(loops))) for i in nloops: - lock = thread.allocate_lock() + lock = _thread.allocate_lock() lock.acquire() locks.append(lock) for i in nloops: - thread.start_new_thread(loop,(i,loops[i],locks[i])) + _thread.start_new_thread(loop,(i,loops[i],locks[i])) for i in nloops: while locks[i].locked():pass - print " all done at:" ,ctime() + print(" all done at:" ,ctime()) if __name__ == "__main__": main() diff --git a/primer/19/label.py b/primer/19/label.py index cec761f..64ac71f 100644 --- a/primer/19/label.py +++ b/primer/19/label.py @@ -1,11 +1,11 @@ -import Tkinter +import tkinter -top = Tkinter.Tk() +top = tkinter.Tk() -label = Tkinter.Label(top,text="input") +label = tkinter.Label(top,text="input") label.pack() -button = Tkinter.Button(top,text="QIUT",command=top.quit,bg="red",fg="white") -button.pack(fill=Tkinter.X,expand=1) +button = tkinter.Button(top,text="QIUT",command=top.quit,bg="red",fg="white") +button.pack(fill=tkinter.X,expand=1) -Tkinter.mainloop() +tkinter.mainloop() diff --git a/primer/2/2_10.py b/primer/2/2_10.py index d2dec79..e9ec7cd 100644 --- a/primer/2/2_10.py +++ b/primer/2/2_10.py @@ -1,10 +1,10 @@ a = 19 -print "please input a int number in 1-100" -x = raw_input() +print("please input a int number in 1-100") +x = input() while x != a: - print "sorry error: \n input again:" - x = raw_input() + print("sorry error: \n input again:") + x = input() if x == a: - print "you are right" + print("you are right") break -raw_input() +input() diff --git a/primer/2/2_11.py b/primer/2/2_11.py index 5c3877d..010f49f 100644 --- a/primer/2/2_11.py +++ b/primer/2/2_11.py @@ -1,25 +1,25 @@ -print "Menu: input the choice\n" -print "s: sum" -print "a: avg" -print "x: exit" +print("Menu: input the choice\n") +print("s: sum") +print("a: avg") +print("x: exit") aa =[1,2,3,4] while True: - ch = raw_input() + ch = input() if ch == 's': i = 0 Sum = 0 - print "you choice sum:\n" + print("you choice sum:\n") for i in aa: Sum += i - print Sum + print(Sum) if ch == 'a': - print "you choice avg:\n" + print("you choice avg:\n") i = 0 Sum1 = 0 for i in aa: Sum1 += i avg = float(Sum1)/(len(aa)) - print avg + print(avg) if ch == 'x': break diff --git a/primer/2/2_7.py b/primer/2/2_7.py index 8405c4b..9cf14db 100644 --- a/primer/2/2_7.py +++ b/primer/2/2_7.py @@ -1,5 +1,5 @@ -s = raw_input() +s = input() i = 0 for i in s: - print i -raw_input() + print(i) +input() diff --git a/primer/2/2_8.py b/primer/2/2_8.py index 7ea33df..468d025 100644 --- a/primer/2/2_8.py +++ b/primer/2/2_8.py @@ -3,5 +3,5 @@ t = 0 for i in s: t += i -print float(t)/len(s) -raw_input() +print(float(t)/len(s)) +input() diff --git a/primer/20/Cralwer.py b/primer/20/Cralwer.py index 3afa5d2..b60cb1c 100644 --- a/primer/20/Cralwer.py +++ b/primer/20/Cralwer.py @@ -5,10 +5,10 @@ from os.path import dirname,exists,isdir,splitext from string import replace,find,lower from htmllib import HTMLParser -from urllib import urlretrieve -from urlparse import urlparse,urljoin +from urllib.request import urlretrieve +from urllib.parse import urlparse,urljoin from formatter import DumbWriter,AbstractFormatter -from cStringIO import StringIO +from io import StringIO class Retriever(object):#下载网页类 @@ -60,35 +60,35 @@ def getPage(self,url): #下载网页 r = Retriever(url) retval = r.download() if retval[0] == "*": #错误,不解析 - print retval,"--- skipping parse" + print(retval,"--- skipping parse") return Crawler.count += 1 - print '\n(',Crawler.count,')' - print "URL:",url - print "FILE:",retval[0] + print('\n(',Crawler.count,')') + print("URL:",url) + print("FILE:",retval[0]) self.seen.append(url) links = r.parseAndGetLinks() #得到链接 for eachLink in links: if eachLink[:4] != "http" and find(eachLink,"://") == -1: eachLink = urljoin(url,eachLink) - print "* ",eachLink + print("* ",eachLink) if find(lower(eachLink),"mailto:") != -1: #过滤邮箱链接 - print "--- discarded,mailto link" + print("--- discarded,mailto link") continue if eachLink not in self.seen: if find(eachLink,self.dom) == -1: - print "---discarded,not in domain" + print("---discarded,not in domain") else: if eachLink not in self.q: self.q.append(eachLink) - print "---new,add to Q" + print("---new,add to Q") else: - print "---discarded,already in Q" + print("---discarded,already in Q") else: - print "---discarded, arlready processed" + print("---discarded, arlready processed") def go(self): #在队列里处理链接,启动 while self.q: @@ -101,7 +101,7 @@ def main(): else: try: - url = raw_input("Enter starting URL:") + url = input("Enter starting URL:") except (KeyboardInterrupt,EOFError): url = "" diff --git a/primer/3/makeFile.py b/primer/3/makeFile.py index bee369a..1cdeca9 100644 --- a/primer/3/makeFile.py +++ b/primer/3/makeFile.py @@ -1,8 +1,8 @@ import os -filename=raw_input("filename:") +filename=input("filename:") if os.path.exists(filename): - print "file exist" + print("file exist") exit() @@ -10,5 +10,5 @@ fd.writelines(all) fd.close() -print "done" +print("done") diff --git a/primer/3/makeTextFile.py b/primer/3/makeTextFile.py index 6969f8f..a67cc34 100644 --- a/primer/3/makeTextFile.py +++ b/primer/3/makeTextFile.py @@ -6,19 +6,19 @@ #get filename while True: - fname = raw_input() + fname = input() if os.path.exists(fname): - print "ERROR: '%s' already exists " %fname + print("ERROR: '%s' already exists " %fname) else: break #get file content lines all = [] -print "\n Enter lines:('.' by itself to quit)\n" +print("\n Enter lines:('.' by itself to quit)\n") #loop until user terminates input while True: - entry = raw_input('>') + entry = input('>') if entry == '.': break else: @@ -28,5 +28,5 @@ fobj = open(fname,'w') fobj.writelines(['%s%s' %(x,ls) for x in all]) fobj.close() -print 'DONE!' +print('DONE!') diff --git a/primer/3/readTextFile.py b/primer/3/readTextFile.py index 980d3e0..7e8bc91 100644 --- a/primer/3/readTextFile.py +++ b/primer/3/readTextFile.py @@ -2,16 +2,16 @@ 'readTextFile.py -- read and display text file' #get filename -fname = raw_input("enter the filename:") -print +fname = input("enter the filename:") +print() #attempt to open file for reading try: fobj = open(fname,'r') -except IOError,e: - print "*** file open error",e +except IOError as e: + print("*** file open error",e) else: #display contents to the screen for echoLine in fobj: - print echoLine; + print(echoLine); fobj.close() diff --git a/primer/4/display.py b/primer/4/display.py index e50f368..0b21d81 100644 --- a/primer/4/display.py +++ b/primer/4/display.py @@ -1,9 +1,9 @@ def displayType(num): - print num, 'is', - if isinstance(num,(int,long,float,complex)): - print "a number of type:",type(num).__name__ + print(num, 'is', end=' ') + if isinstance(num,(int,float,complex)): + print("a number of type:",type(num).__name__) else: - print "not a number at all" + print("not a number at all") displayType(2) displayType(-1.9) diff --git a/primer/6/idcheck.py b/primer/6/idcheck.py index b6d6220..962031c 100644 --- a/primer/6/idcheck.py +++ b/primer/6/idcheck.py @@ -3,18 +3,18 @@ alphas = string.letters +'_' nums = string.digits -print "Welcom to the indetifter Checker V1.0" -print "Test must be at least 2 Chars long" -myinput = raw_input("Iddentifter to test:\n") +print("Welcom to the indetifter Checker V1.0") +print("Test must be at least 2 Chars long") +myinput = input("Iddentifter to test:\n") if len(myinput) > 1: if myinput[0] not in alphas: - print "invald: first symbol must be alphbetic" + print("invald: first symbol must be alphbetic") else: for otherChar in myinput[1:]: if alphas not in alphas + nums: - print "invalid:remaining symbols must be alphanumeric" + print("invalid:remaining symbols must be alphanumeric") break else: - print "ok as an identifier" -raw_input() + print("ok as an identifier") +input() diff --git a/primer/6/queue.py b/primer/6/queue.py index 7eb364d..bb97049 100644 --- a/primer/6/queue.py +++ b/primer/6/queue.py @@ -1,14 +1,14 @@ queue = [] def enQ(): - queue.append(raw_input("enter new string:").strip()) + queue.append(input("enter new string:").strip()) def deQ(): if len(queue) == 0: - print "empty queue\n" + print("empty queue\n") else: - print 'Removed![',`queue.pop()`,']' + print('Removed![',repr(queue.pop()),']') def viewQ(): - print queue + print(queue) CMDS = {'e': enQ,'d':deQ,'v':viewQ} def showmenu(): @@ -22,12 +22,12 @@ def showmenu(): while True: while True: try: - choice = raw_input(pr).strip()[0].lower() + choice = input(pr).strip()[0].lower() except (EOFError,KeyboardInterpt,IndexError): choice = "q" - print "\nYou picked:[%s]" % choice + print("\nYou picked:[%s]" % choice) if choice not in "devq": - print "error,try again" + print("error,try again") else: break if choice == "q": diff --git a/primer/6/stack.py b/primer/6/stack.py index 60dc053..f63d14e 100644 --- a/primer/6/stack.py +++ b/primer/6/stack.py @@ -1,16 +1,16 @@ stack = [] def pushit(): - stack.append(raw_input("enter a string:").strip()) + stack.append(input("enter a string:").strip()) def popit(): if len(stack) == 0: - print "stack is empty!\n" + print("stack is empty!\n") else: - print 'Removed![',`stack.pop()`,']' + print('Removed![',repr(stack.pop()),']') def viewstack(): - print stack + print(stack) CMDS ={'u': pushit,'o':popit,'v':viewstack} @@ -25,13 +25,13 @@ def showmenu(): while True: while True: try: - choice = raw_input(pr).strip()[0].lower() + choice = input(pr).strip()[0].lower() except (EOFError,KeyboardInterrupt,IndexError): choice ="q" - print "\nYou picked:[%s]" % choice + print("\nYou picked:[%s]" % choice) if choice not in "uovq": - print "Invalid option,try again" + print("Invalid option,try again") else: break diff --git a/primer/6/unicodeFile.py b/primer/6/unicodeFile.py index 0752725..090dc6c 100644 --- a/primer/6/unicodeFile.py +++ b/primer/6/unicodeFile.py @@ -5,7 +5,7 @@ CODEC = "utf-8" FILE = "unicode.txt" -hello = u"hhhh\n" +hello = "hhhh\n" byte = hello.encode(CODEC) f = open(FILE,"w") f.write(byte) @@ -16,5 +16,5 @@ f.close() hello = byte.decode(CODEC) -print hello -raw_input() +print(hello) +input() diff --git a/primer/7/userpw.py b/primer/7/userpw.py index ebe358e..a2e597f 100644 --- a/primer/7/userpw.py +++ b/primer/7/userpw.py @@ -3,24 +3,24 @@ def newuser(): prompt = "login desired:" while True: - name = raw_input(prompt) - if db.has_key(name): + name = input(prompt) + if name in db: prompt = "name taken,try again: " continue else: break - pwd = raw_input("passwd:") + pwd = input("passwd:") db[name]= pwd - print "regeisted oK!\n" + print("regeisted oK!\n") def olduser(): - name = raw_input("login:") - pwd = raw_input("passwd:") + name = input("login:") + pwd = input("passwd:") passwd = db.get(name) if passwd == pwd: - print "welcome back," ,name + print("welcome back," ,name) else: - print "login incorrect" + print("login incorrect") def showmenu(): prompt = """ @@ -34,12 +34,12 @@ def showmenu(): chosen = False while not chosen: try: - choice = raw_input(prompt).strip()[0].lower() + choice = input(prompt).strip()[0].lower() except(EOFError,KeyboardInterrupt): choice = "q" - print "\n you picked [%s]" % choice + print("\n you picked [%s]" % choice) if choice not in "nlq": - print "invalid option, try again" + print("invalid option, try again") else: chosen = True diff --git a/primer/9/ospathex.py b/primer/9/ospathex.py index a333211..32c6301 100644 --- a/primer/9/ospathex.py +++ b/primer/9/ospathex.py @@ -4,35 +4,35 @@ if os.path.isdir(tmpdir): break else: - print "no temp dir available" + print("no temp dir available") tmpdir = "" if tmpdir: os.chdir(tmpdir) cwd = os.getcwd() - print " current tmp dir" - print cwd + print(" current tmp dir") + print(cwd) - print "create example dir" + print("create example dir") os.mkdir("example") os.chdir("example") cwd = os.getcwd() - print "new work dir" - print cwd - print "list the dir" - print os.listdir(cwd) + print("new work dir") + print(cwd) + print("list the dir") + print(os.listdir(cwd)) - print "create test file" + print("create test file") fobj = open("test","w") fobj.write("xxg\n") fobj.write("111111") fobj.close() - print "update the list dir" - print os.listdir(cwd) + print("update the list dir") + print(os.listdir(cwd)) - print "rename the file" + print("rename the file") os.rename("test","xxg.txt") - print os.listdir(cwd) + print(os.listdir(cwd)) diff --git a/unp/1/download.py b/unp/1/download.py index 253caf1..a53668b 100644 --- a/unp/1/download.py +++ b/unp/1/download.py @@ -1,8 +1,8 @@ #!/usr/bin/env python -import urllib,sys +import urllib.request, urllib.parse, urllib.error,sys -f=urllib.urlopen(sys.argv[1]) +f=urllib.request.urlopen(sys.argv[1]) while True: buf = f.read(2048) diff --git a/unp/1/gopherclient2.py b/unp/1/gopherclient2.py index 5b1b954..ac8e939 100644 --- a/unp/1/gopherclient2.py +++ b/unp/1/gopherclient2.py @@ -12,8 +12,8 @@ try: s.connect((host,port)) -except socket.gaierror,e: - print "Error connecting to server:%s" % e +except socket.gaierror as e: + print("Error connecting to server:%s" % e) sys.exit(1) s.sendall(filename + "\r\n") diff --git a/unp/1/server.py b/unp/1/server.py index ca441c7..026d454 100644 --- a/unp/1/server.py +++ b/unp/1/server.py @@ -10,7 +10,7 @@ s.bind((host,porr)) s.listen(1) -print "server is runing on port %d" % port +print("server is runing on port %d" % port) while 1: clientsock,clientaddr=s.accept() diff --git a/unp/2/connect.py b/unp/2/connect.py index 2938a35..43b0c5b 100644 --- a/unp/2/connect.py +++ b/unp/2/connect.py @@ -2,11 +2,11 @@ import socket -print "create socket" +print("create socket") s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) -print "done" +print("done") -print "connecting to the host" +print("connecting to the host") s.connect(('localhost',8888)) -print "done" +print("done") diff --git a/unp/2/connect1.py b/unp/2/connect1.py index f1efdd4..8f70252 100644 --- a/unp/2/connect1.py +++ b/unp/2/connect1.py @@ -2,15 +2,15 @@ import socket -print "create socket" +print("create socket") s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) -print "done" +print("done") -print "look up port number" +print("look up port number") port=socket.getservbyname('http','tcp') -print "done" +print("done") -print "connecting to the host on port %d" % port +print("connecting to the host on port %d" % port) s.connect(("www.baidu.com",port)) -print "done" +print("done") diff --git a/unp/2/connect3.py b/unp/2/connect3.py index 559e5fa..9e6ad36 100644 --- a/unp/2/connect3.py +++ b/unp/2/connect3.py @@ -2,18 +2,18 @@ import socket -print "create socket" +print("create socket") s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) -print "done" +print("done") -print "look up port number" +print("look up port number") port=socket.getservbyname('http','tcp') -print "done" +print("done") -print "connecting to the host on port %d" % port +print("connecting to the host on port %d" % port) s.connect(("www.baidu.com",port)) -print "done" +print("done") -print "connected from",s.getsockname() -print "connected to",s.getpeername() +print("connected from",s.getsockname()) +print("connected to",s.getpeername()) diff --git a/unp/2/socketerrors.py b/unp/2/socketerrors.py index f7dc995..c01e4ce 100644 --- a/unp/2/socketerrors.py +++ b/unp/2/socketerrors.py @@ -8,8 +8,8 @@ try: s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) -except socket.error,e: - print "strange erroe create socket %s" % e +except socket.error as e: + print("strange erroe create socket %s" % e) sys.exit(1) @@ -18,7 +18,7 @@ except ValueError: try: port=socket.getservbyname(textport,'tcp') - except socket.error,e: - print "could find you port %s" % e + except socket.error as e: + print("could find you port %s" % e) sys.exit(1) diff --git a/unp/2/udp.py b/unp/2/udp.py index 7c950e5..7a8c9ad 100644 --- a/unp/2/udp.py +++ b/unp/2/udp.py @@ -15,12 +15,12 @@ s.connect((host,port)) -print "enter data to tranmit:" +print("enter data to tranmit:") data=sys.stdin.readline().strip() s.sendall(data) -print "looking for replies;" +print("looking for replies;") while 1: buf=s.recv(2048) diff --git a/unp/3/basicserver.py b/unp/3/basicserver.py index 1977ee0..2458d22 100644 --- a/unp/3/basicserver.py +++ b/unp/3/basicserver.py @@ -8,11 +8,11 @@ s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((host,port)) -print "waiting for connect..." +print("waiting for connect...") s.listen(1) while 1: clientsock,clientaddr=s.accept() - print "Go connection from ,", clientsock.getpeername() + print("Go connection from ,", clientsock.getpeername()) clientsock.close() diff --git a/unp/3/echoclient.py b/unp/3/echoclient.py index 7b5e002..82bed56 100644 --- a/unp/3/echoclient.py +++ b/unp/3/echoclient.py @@ -20,7 +20,7 @@ s.shutdown(1) -print "All data sent" +print("All data sent") while 1: buf=s.recv(1024) if not len(buf): diff --git a/unp/3/echoserver.py b/unp/3/echoserver.py index 4e2a6ee..c36f015 100644 --- a/unp/3/echoserver.py +++ b/unp/3/echoserver.py @@ -21,7 +21,7 @@ continue try: - print "Got connection from " ,clientsock.getpeername() + print("Got connection from " ,clientsock.getpeername()) while 1: data= clientsock.recv(4096) if not len(data): diff --git a/unp/3/socketop.py b/unp/3/socketop.py index 073e6dd..1553e0b 100644 --- a/unp/3/socketop.py +++ b/unp/3/socketop.py @@ -6,4 +6,4 @@ solist.sort() for x in solist: - print x + print(x) diff --git a/unp/3/syslogsample.py b/unp/3/syslogsample.py index 6faf4a2..2d20fa5 100644 --- a/unp/3/syslogsample.py +++ b/unp/3/syslogsample.py @@ -1,7 +1,7 @@ #!/usr/bin env python #!--coding: utf-8-- -import syslog,StringIO,sys,os,traceback +import syslog,io,sys,os,traceback def logexception(includetraceback=0): exctype,exception,exctraceback=sys.exc_info() @@ -11,7 +11,7 @@ def logexception(includetraceback=0): if not includetraceback: syslog.syslog(syslog.LOG_ERR,"%s: %s" % (excclass,message)) else: - excfd=StringIO.StringIO() + excfd=io.StringIO() traceback.print_exception(exctype,exception,exctraceback,None,excfd) for line in excfd.getvalue().split("\n"): @@ -25,12 +25,12 @@ def initsyslog(): initsyslog() try: - raise RuntimeError, "Exception 1" + raise RuntimeError("Exception 1") except: logexception(0) try: - raise RuntimeError, "Exception 2" + raise RuntimeError("Exception 2") except: logexception(1) diff --git a/unp/3/udpechoserver.py b/unp/3/udpechoserver.py index dc6cdcb..37db109 100644 --- a/unp/3/udpechoserver.py +++ b/unp/3/udpechoserver.py @@ -12,7 +12,7 @@ while 1: try: message,address=s.recvfrom(8192) - print "Go data from",address + print("Go data from",address) s.sendall(message,address) except (keyboardInterrupt,SystemExit): raise diff --git a/unp/3/xinetdserver.py b/unp/3/xinetdserver.py index 492b0cb..b346f6b 100644 --- a/unp/3/xinetdserver.py +++ b/unp/3/xinetdserver.py @@ -1,11 +1,11 @@ #/usr/bin env python import sys -print "welcome...." -print "please enter a string:" +print("welcome....") +print("please enter a string:") sys.stdout.flush() line=sys.stdin.readline().strip() -print "you enter the %s is %d count" % (line,len(line)) +print("you enter the %s is %d count" % (line,len(line))) diff --git a/unp/4/dns.py b/unp/4/dns.py index 5923b53..bd80602 100644 --- a/unp/4/dns.py +++ b/unp/4/dns.py @@ -9,7 +9,7 @@ answerobj=reqobj.req(name=query,qtype=DNS.Type.ANY) if not len(answerobj.answers): - print "not find" + print("not find") for i in answerobj.answers: - print "%-5s %s " % (i['typename'],i['data']) + print("%-5s %s " % (i['typename'],i['data'])) diff --git a/unp/4/environment.py b/unp/4/environment.py index e29251f..408b1fd 100644 --- a/unp/4/environment.py +++ b/unp/4/environment.py @@ -7,11 +7,11 @@ def getipaddrs(hostname): return [x[4][0] for x in s] hostname=socket.gethostname() -print "Host name:",hostname +print("Host name:",hostname) -print "full-name:",socket.getfqdn(hostname) +print("full-name:",socket.getfqdn(hostname)) try: - print "IP address:",", ".join(getipaddrs(hostname)) -except socket.gaierror,e: - print "can not get ip address",e + print("IP address:",", ".join(getipaddrs(hostname))) +except socket.gaierror as e: + print("can not get ip address",e) diff --git a/unp/4/getaddrinfo.py b/unp/4/getaddrinfo.py index 5d01ae6..3752edf 100644 --- a/unp/4/getaddrinfo.py +++ b/unp/4/getaddrinfo.py @@ -6,7 +6,7 @@ counter=0 for i in s: - print "%d %s" % (counter,s[counter][4]) + print("%d %s" % (counter,s[counter][4])) counter += 1 diff --git a/unp/4/gethostbyaddr.py b/unp/4/gethostbyaddr.py index 4eb61c5..bfde530 100644 --- a/unp/4/gethostbyaddr.py +++ b/unp/4/gethostbyaddr.py @@ -6,14 +6,14 @@ s=socket.gethostbyaddr(sys.argv[1]) - print "hostname:" - print " "+ s[0] + print("hostname:") + print(" "+ s[0]) - print "\nAddress:" + print("\nAddress:") for i in s[2]: - print " " + i + print(" " + i) -except socket.herror,e: - print "can not look up name:",e +except socket.herror as e: + print("can not look up name:",e) diff --git a/unp/5/bcastclinet.py b/unp/5/bcastclinet.py index 8ed2d3a..498848b 100644 --- a/unp/5/bcastclinet.py +++ b/unp/5/bcastclinet.py @@ -14,7 +14,7 @@ while 1: try: message,address=s.recvfrom(8192) - print "Got data from",addrrss + print("Got data from",addrrss) s.sendto("I am here",address) except (KeyboardInterrupt,SystemExit): raise diff --git a/unp/5/bcastserver.py b/unp/5/bcastserver.py index 0332651..bf262db 100644 --- a/unp/5/bcastserver.py +++ b/unp/5/bcastserver.py @@ -8,9 +8,9 @@ s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1) s.sendto("hello",dest) -print "look for replies ...." +print("look for replies ....") while 1: (buf,address)=s.recvfrom(2048) if not len(buf): break - print "Recived from %s: %s" % (address,buf) + print("Recived from %s: %s" % (address,buf)) diff --git a/unp/5/delayserver.py b/unp/5/delayserver.py index 388d6f9..12ed9e4 100644 --- a/unp/5/delayserver.py +++ b/unp/5/delayserver.py @@ -22,7 +22,7 @@ continue try: - print "get connect from",clientsock.getpeername() + print("get connect from",clientsock.getpeername()) while 1: try: clientsock.sendall(time.asctime() + "\n") diff --git a/unp/5/nbo.py b/unp/5/nbo.py index f82760b..a4d3192 100644 --- a/unp/5/nbo.py +++ b/unp/5/nbo.py @@ -17,7 +17,7 @@ def ntohl(data): def sendstring(data): return htonl(len(data)) + data -print "Enter a string:" +print("Enter a string:") str=sys.stdin.readline().rstrip() -print repr(sendstring(str)) +print(repr(sendstring(str))) diff --git a/unp/5/pollclient.py b/unp/5/pollclient.py index 61c32b0..952ad02 100644 --- a/unp/5/pollclient.py +++ b/unp/5/pollclient.py @@ -34,12 +34,12 @@ def spin(): if results[0][1] == select.POLLIN: data = s.recv(4096) if not len(data): - print "Remote end closed connect" + print("Remote end closed connect") break sys.stdout.write("\rReceived:" + data) sys.stdout.flush() else: - print "\rproblem occurred ; exiting" + print("\rproblem occurred ; exiting") sys.exit(0) spin() diff --git a/unp/5/selectclient.py b/unp/5/selectclient.py index 03cc94b..cf49e80 100644 --- a/unp/5/selectclient.py +++ b/unp/5/selectclient.py @@ -30,14 +30,14 @@ def spin(): if len(infds): data=s.recv(4096) if not len(data): - print "\rRemote end closed connection; exiting" + print("\rRemote end closed connection; exiting") break sys.stdout.write("\rRecived: " + data) sys.stdout.flush() if len(errfds): - print "\r problem occurred; exiting" + print("\r problem occurred; exiting") sys.exit(0) spin() diff --git a/unp/5/timeoutserver.py b/unp/5/timeoutserver.py index 229476d..da684c2 100644 --- a/unp/5/timeoutserver.py +++ b/unp/5/timeoutserver.py @@ -23,7 +23,7 @@ clientsock.settimeout(5) try: - print "get connect from",clientsock.getpeername() + print("get connect from",clientsock.getpeername()) while 1: data=clientsock.recv(4096) if not len(data): diff --git a/unp/6/dump_info.py b/unp/6/dump_info.py index d351719..402bf5c 100644 --- a/unp/6/dump_info.py +++ b/unp/6/dump_info.py @@ -1,12 +1,12 @@ #!/usr/bin env python -import sys,urllib2 +import sys,urllib.request,urllib.error,urllib.parse -req=urllib2.Request(sys.argv[1]) -fd=urllib2.urlopen(req) +req=urllib.request.Request(sys.argv[1]) +fd=urllib.request.urlopen(req) -print "Retrieved",fd.geturl() +print("Retrieved",fd.geturl()) info=fd.info() -for key,value in info.items(): - print "%s = %s " % ( key,value) +for key,value in list(info.items()): + print("%s = %s " % ( key,value)) diff --git a/unp/6/dump_page.py b/unp/6/dump_page.py index b550f63..8a61192 100644 --- a/unp/6/dump_page.py +++ b/unp/6/dump_page.py @@ -1,9 +1,9 @@ #!/usr/bin env python -import sys,urllib2 +import sys,urllib.request,urllib.error,urllib.parse -req=urllib2.Request(sys.argv[1]) -fd=urllib2.urlopen(req) +req=urllib.request.Request(sys.argv[1]) +fd=urllib.request.urlopen(req) while 1: data=fd.read(1024)