浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Python可变参数与标准输出的重定位 « Xiaoxia[PG]

Python可变参数与标准输出的重定位

使用Python的内置函数print支持可变参数,也就是说,print的调用参数是不固定的。例如:

  1. # 一个参数  
  2. print "Hello China!"  
  3. # 两个参数  
  4. print "Your name is", name  
  5. # 三个参数  
  6. print "The number of", what, "is", count, "!"  

在Python里使用*和**来设置可变参数,它们的区别是*传递一个参数列表(准确来说是参数元组),**传递一个参数字典。二者可以同时混合使用。

  1. >>> def printArgs(*argList, **argDict):  
  2. ...     print "argList =", argList, ", argDict =", argDict  
  3. ...  
  4. >>> printArgs("The end of the world is"2012, lastMan = "Xiaoxia")  
  5. argList = ('The end of the world is'2012) , argDict = {'lastMan''Xiaoxia'}  

下面举一个例子来模仿print的实现,

  1. >>> import sys  
  2. >>> def myprint(*argv):  
  3. ...     sys.stdout.write(" ".join([str(i) for i in argv]) + "\n")  
  4. ...  
  5. >>> print "I believe"2012"is the end of the world."  
  6. I believe 2012 is the end of the world.  
  7. >>> myprint("I believe"2012"is the end of the world.")  
  8. I believe 2012 is the end of the world.  
  9. >>> print "tuple:", (123), "list:", [123], "dict:", {"begin":-2012"end":2012}  
  10. tuple: (123) list: [123] dict: {'begin': -2012'end'2012}  
  11. >>> myprint("tuple:", (123), "list:", [123], "dict:", {"begin":-2012"end":2012})  
  12. tuple: (123) list: [123] dict: {'begin': -2012'end'2012}  

print默认是输出到stdout中,在终端运行的程序,无重定向的情况下,print输出到控制台。如果要做代码里实现把print的输出写入到log文件中,可以通过修改stdout的文件对象来实现。同理,重定位标准输入和标准错误输出分别修改stdin和stderr的文件对象即可。

下面的例子捕捉所有print的输出,让输出的每一行前增加一个时间的显示:

  1. import sys, time  
  2.   
  3. class MyOutput():  
  4.     def __init__(self, fd):  
  5.         self.formatTime()  
  6.         self.out = fd  
  7.         self.newLine = True  
  8.   
  9.     def formatTime(self):  
  10.         return time.strftime("%H:%M:%S  ", time.localtime())  
  11.   
  12.     def write(self, s):  
  13.         if self.newLine:  
  14.             self.out.write(self.formatTime())  
  15.             self.newLine = False  
  16.         self.out.write(s)  
  17.         if s.endswith("\n"):  
  18.             self.newLine = True  
  19.   
  20.     def flush(self):  
  21.         self.out.flush()  
  22.   
  23. sys.stdout = MyOutput(sys.stdout)  
  24.   
  25. print "Program begin."  
  26. mylist = [54321]  
  27. print "prev:  ", mylist  
  28. mylist.sort()  
  29. print "after: ", mylist  
  30. time.sleep(3)  
  31. print "Program end."  

运行效果:

root@xiaoxia-pc:~/桌面# python redirect.py
02:25:41 Program begin.
02:25:41 prev: [5, 4, 3, 2, 1]
02:25:41 after: [1, 2, 3, 4, 5]
02:25:44 Program end.

posted on 2012-03-04 11:45  lexus  阅读(378)  评论(0编辑  收藏  举报