def print(stream): """ print(value, ..., sep=' ', end='\\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. """ pass
In [2]: print ('a', 'b', sep='|') File "<ipython-input-2-bcb798285c07>", line 1 print ('a', 'b', sep='|') ^ SyntaxError: invalid syntax
In [6]: print('a', 'b') a b In [7]: print('a', 'b', sep='--') #print 多个values 不用逗号分隔 a--b In [8]: print('nihao');print('orangle') nihao orangle In [9]: print('nihao', end='');print('orangle') #print 不换行 nihaoorangle
In [11]: f = open('test.txt', 'w') In [12]: print('haha.....csdn', file=f) In [15]: ls test.txt 驱动器 D 中的卷没有标签。 卷的序列号是 0002-FA2E D:\code\python 的目录 2015/01/20 周二 10:37 0 test.txt 1 个文件 0 字节 0 个目录 61,124,526,080 可用字节 In [16]: f.close()
def write(self, str): """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ return ""
In [3]: class A(): ...: def __str__(self): ...: return "A" ...: In [5]: a = A() In [6]: print a A In [9]: import sys In [10]: sys.stdout.write(a) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-0697f962911e> in <module>() ----> 1 sys.stdout.write(a) TypeError: expected a character buffer object In [11]: sys.stdout.write(str(a)) A
import sys temp = sys.stdout #store original stdout object for later sys.stdout = open('log.txt','w') #redirect all prints to this log file print("testing123") #nothing appears at interactive prompt print("another line") #again nothing appears. It is instead written to log file sys.stdout.close() #ordinary file object sys.stdout = temp #restore print commands to interactive prompt print("back to normal") #this shows up in the interactive prompt
testing123 another line
本文出自 “orangleliu笔记本” 博客,转载请务必保留此出处http://blog.csdn.net/orangleliu/article/details/42915501
作者orangleliu 采用署名-非商业性使用-相同方式共享协议
[Python]print vs sys.stdout.write
原文地址:http://blog.csdn.net/orangleliu/article/details/42915501