1. 程式人生 > >python sys中的stdin,stdout,stderr

python sys中的stdin,stdout,stderr

  1. #testing stdout  
  2. >>> print 'Hello World!' #該語句會在標準輸出的螢幕上列印 Hello World!  
  3. Hello World!  
  4. #等價於:  
  5. >>> import sys  
  6. >>> sys.stdout.write('Hello World!\n')  
  7. Hello World!  

  

  1. import sys  
  2. print 'Please enter your name:',  
  3. name=sys.stdin.readline()[:-1]  #輸入等同於input
  4. print 'Hi,%s!' % name  

  內部邏輯實現-----重定向

  Python提供了一個StringIO模組來完成這個設想,比如:

  1. >>> from StringIO import StringIO  
  2. >>> import sys  
  3. >>> buf=StringIO()  
  4. >>> temp=sys.stdout #重定向前儲存stdout  
  5. >>> sys.stdout=buf  #將stdout重定向到buff物件  
  6. >>> print 825,'python',0,666  # print會在要列印的資訊後面加上一個硬回車  
  7. >>> sys.stdout=temp  #恢復stdout  
  8. >>> buf.getvalue() # print會在要列印的資訊後面加上一個硬回車,因此最後有一個'\n'  
  9. '825 python 0 666\n'