zoukankan      html  css  js  c++  java
  • python中sys.stdout、sys.stdin

    如果需要更好的控制输出,而print不能满足需求,sys.stdout,sys.stdin,sys.stderr就是你需要的。

    1. sys.stdout与print:

    在python中调用print时,事实上调用了sys.stdout.write(obj+' ')

    print 将需要的内容打印到控制台,然后追加一个换行符

    以下两行代码等价:

    sys.stdout.write('hello' + '
    ')
    print('hello')

    2. sys.stdin与input

    sys.stdin.readline( )会将标准输入全部获取,包括末尾的' ',因此用len计算长度时是把换行符' '算进去了的,但是input( )获取输入时返回的结果是不包含末尾的换行符' '的。

    因此如果在平时使用sys.stdin.readline( )获取输入的话,不要忘了去掉末尾的换行符,可以用strip( )函数(sys.stdin.readline( ).strip(' '))或sys.stdin.readline( )[:-1]这两种方法去掉换行。

    import sys
    hi1=input()
    hi2=sys.stdin.readline()
    print(len(hi1))
    print(len(hi2))

    结果如下:

    PS C:	est> python 2.py
    123
    123
    3
    4

    3. 从控制台重定向到文件

    原始的sys.stdout指向控制台,如果把文件的对象引用赋给sys.stdout,那么print调用的就是文件对象的write方法。

    import sys
    sys.stdout = open('test.txt','w')
    print 'Hello world'

    恢复默认映射

    import sys
    temp = sys.stdout
    sys.stdout = open('test.txt','w')
    print 'hello world'
    sys.stdout = temp #恢复默认映射关系
    print 'nice'

    赋值到自定义对象

    class Test:
    	def write(self,string):
    		#do something you wanna do
    test = Test()
    temp = sys.stdout
    sys.stdout = test
    print 'hello world'
    天道酬勤 循序渐进 技压群雄
  • 相关阅读:
    nginx负载均衡
    Zabbix的安装和使用
    JENKINS安装和使用
    docker-compose安装
    gitlab的安装和使用
    Surging填坑记
    SQL2008R2下数据库修复一例
    SQL2000下修复某数据库的经历
    《C++ Primer Plus 第6版》学习笔记
    C++常见笔试题
  • 原文地址:https://www.cnblogs.com/wuyuan2011woaini/p/15131522.html
Copyright © 2011-2022 走看看