zoukankan      html  css  js  c++  java
  • Xiaoxia[PG] Python可变参数与标准输出的重定位

    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.

  • 相关阅读:
    Git中清除远程仓库HTTPS认证信息的方法
    JDK8新增时间类型用在JPA中的问题
    5 个关于 API 中日期和时间设计规则
    时间标准基础知识UTC和ISO8601
    JDK8中的时间API
    2019第7周日
    顶级思维模式:推导事物的第一性原理
    JS的jsoneditor,用来操作Json格式的界面;json-editor用来根据json数据生成界面
    Java读写文件,中文乱码解决
    intellij idea 热部署、热加载设置方法
  • 原文地址:https://www.cnblogs.com/lexus/p/2379119.html
Copyright © 2011-2022 走看看