Python可变参数与标准输出的重定位 « Xiaoxia[PG]
Python可变参数与标准输出的重定位
使用Python的内置函数print支持可变参数,也就是说,print的调用参数是不固定的。例如:
- # 一个参数
- print "Hello China!"
- # 两个参数
- print "Your name is", name
- # 三个参数
- print "The number of", what, "is", count, "!"
在Python里使用*和**来设置可变参数,它们的区别是*传递一个参数列表(准确来说是参数元组),**传递一个参数字典。二者可以同时混合使用。
- >>> def printArgs(*argList, **argDict):
- ... print "argList =", argList, ", argDict =", argDict
- ...
- >>> printArgs("The end of the world is", 2012, lastMan = "Xiaoxia")
- argList = ('The end of the world is', 2012) , argDict = {'lastMan': 'Xiaoxia'}
下面举一个例子来模仿print的实现,
- >>> import sys
- >>> def myprint(*argv):
- ... sys.stdout.write(" ".join([str(i) for i in argv]) + "\n")
- ...
- >>> print "I believe", 2012, "is the end of the world."
- I believe 2012 is the end of the world.
- >>> myprint("I believe", 2012, "is the end of the world.")
- I believe 2012 is the end of the world.
- >>> print "tuple:", (1, 2, 3), "list:", [1, 2, 3], "dict:", {"begin":-2012, "end":2012}
- tuple: (1, 2, 3) list: [1, 2, 3] dict: {'begin': -2012, 'end': 2012}
- >>> myprint("tuple:", (1, 2, 3), "list:", [1, 2, 3], "dict:", {"begin":-2012, "end":2012})
- tuple: (1, 2, 3) list: [1, 2, 3] dict: {'begin': -2012, 'end': 2012}
print默认是输出到stdout中,在终端运行的程序,无重定向的情况下,print输出到控制台。如果要做代码里实现把print的输出写入到log文件中,可以通过修改stdout的文件对象来实现。同理,重定位标准输入和标准错误输出分别修改stdin和stderr的文件对象即可。
下面的例子捕捉所有print的输出,让输出的每一行前增加一个时间的显示:
- import sys, time
- class MyOutput():
- def __init__(self, fd):
- self.formatTime()
- self.out = fd
- self.newLine = True
- def formatTime(self):
- return time.strftime("%H:%M:%S ", time.localtime())
- def write(self, s):
- if self.newLine:
- self.out.write(self.formatTime())
- self.newLine = False
- self.out.write(s)
- if s.endswith("\n"):
- self.newLine = True
- def flush(self):
- self.out.flush()
- sys.stdout = MyOutput(sys.stdout)
- print "Program begin."
- mylist = [5, 4, 3, 2, 1]
- print "prev: ", mylist
- mylist.sort()
- print "after: ", mylist
- time.sleep(3)
- 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.