[Python3.6] print vs sys.stdout.write

Print 输出方法

使用dir()

 如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:

>>> dir('123456')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:

>>> len('123456')
6
>>> '123456'.__len__()
6
>>> 

每个函数对象都是有一个__doc__的属性。通过显示__doc__,我们可以查看一些内部函数的帮助信息

查看print属性

>>> dir(print)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
>>> print.__doc__
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
>>>

我们把print的帮助信息整理一下:

1 def print(stream):  
2   """ print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)
3    
4   Prints the values to a stream, or to sys.stdout by default. 
5   Optional keyword arguments:                                            #可选参数
6   file: a file-like object (stream); defaults to the current sys.stdout. #将文本输入到file-like对象中,可以是文件,数据流等等,默认是sys.stdout
7   sep:  string inserted between values, default a space.                 #把字符串插入值(value1,value2,value3,…)之间,默认一个空格
8   end:  string appended after the last value, default a newline.         #字符串追加在最后一个值后面,默认是一个换行符。
9
flush: whether to forcibly flush the stream. #flush值为True或者False,默认为Flase,表示是否立刻将输出语句输入到参数file指向的对象中(默认是sys.stdout)例如:
10  """  

11 pass

 举例:

=============================== RESTART: Shell ===============================
>>> print('你好,中国')
你好,中国
>>> print('你好,','中国',sep='&&')
你好,&&中国
>>> print('你好,中国',end='@@')#以符号@结尾,默认是换行符'\n'
你好,中国@@

 >>> f.close()
  >>> f = open('test.txt', 'w')
  >>> print('你好,中国',file=f)  #这条语句执行完毕之后,字符串'你好,中国'依然在内存中以文件流的形式
  >>> f.close()     #当关闭文件后,才可以在文件中查看
  >>>

#到对应的目录下看看,test.txt的内容, '你好,中国', 不过一定要记得 f.close(), 如果不关闭,内容是无法保存到文件中的。

  >>> f = open('test.txt', 'w')
  >>> print('你好,世界',file=f,flush=True)#当flush=True,这条语句执行完毕之后,字符串'你好,世界' 会被立即保写入文件中。可以在文件中看到。
  >>> f.close() #关闭文件
  >>>

 

sys.stdout.write

 这个方法调用的是 ,file 对象中的write方法 ,把字符写到标准输出中,看起来跟print 差不多。

查看文件的属性  

>>> f = open('test.txt', 'w')  #定义一个文件对象f
>>> dir(f)
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed',
'_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read',
'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines'] >>>

  >>> f.write
<built-in method write of _io.TextIOWrapper object at 0x0000000002E1A990> #内置方法

 

>>> import sys
>>> x='你好,中国'
>>> sys.stdout.write(x)
你好,中国
>>> sys.stdout.write(x+'\n')
你好,中国

>>> sys.stdout.write(x)
你好,中国5
>>> import sys; x = 'runoob'; sys.stdout.write(x + '\n')
runoob

>>> 

sys是python自带模块.

 利用 import 语句输入sys 模块。 
当执行import sys后, python在 sys.path 变量中所列目录中寻找 sys 模块文件。然后运行这个模块的主块中的语句进行初始化,然后就可以使用模块了 。

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames',
'_debugmallocstats', '_enablelegacywindowsfsencoding', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing',
'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks',
'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof',
'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value', 'maxsize', 'maxunicode',
'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval',
'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver'] >>>

sys文档

>>> s=sys.__doc__
>>> print(s)
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:

argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules

displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
  To customize printing in an interactive session or to install a custom
  top-level exception handler, assign other functions to replace these.

stdin -- standard input file object; used by input()
stdout -- standard output file object; used by print()#标准输出文件对象;由 print()调用
stderr -- standard error object; used for error messages
  By assigning other file objects (or objects that behave like files)
  to these, it is possible to redirect all of the interpreter's I/O.

last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
  These three are only available in an interactive session after a
  traceback has been printed.

Static objects:

builtin_module_names -- tuple of module names built into this interpreter
copyright -- copyright notice pertaining to this interpreter
exec_prefix -- prefix used to find the machine-specific Python library
executable -- absolute path of the executable binary of the Python interpreter
float_info -- a struct sequence with information about the float implementation.
float_repr_style -- string indicating the style of repr() output for floats
hash_info -- a struct sequence with information about the hash algorithm.
hexversion -- version information encoded as a single integer
implementation -- Python implementation information.
int_info -- a struct sequence with information about the int implementation.
maxsize -- the largest supported length of containers.
maxunicode -- the value of the largest Unicode code point
platform -- platform identifier
prefix -- prefix used to find the Python library
thread_info -- a struct sequence with information about the thread implementation.
version -- the version of this interpreter as a string
version_info -- version information as a named tuple
dllhandle -- [Windows only] integer handle of the Python DLL
winver -- [Windows only] version number of the Python DLL
_enablelegacywindowsfsencoding -- [Windows only] 
__stdin__ -- the original stdin; don't touch!
__stdout__ -- the original stdout; don't touch!
__stderr__ -- the original stderr; don't touch!
__displayhook__ -- the original displayhook; don't touch!
__excepthook__ -- the original excepthook; don't touch!

Functions:

displayhook() -- print an object to the screen, and save it in builtins._
excepthook() -- print an exception and its traceback to sys.stderr
exc_info() -- return thread-safe information about the current exception
exit() -- exit the interpreter by raising SystemExit
getdlopenflags() -- returns flags to be used for dlopen() calls
getprofile() -- get the global profiling function
getrefcount() -- return the reference count for an object (plus one :-)
getrecursionlimit() -- return the max recursion depth for the interpreter
getsizeof() -- return the size of an object in bytes
gettrace() -- get the global debug tracing function
setcheckinterval() -- control how often the interpreter checks for events
setdlopenflags() -- set the flags to be used for dlopen() calls
setprofile() -- set the global profiling function
setrecursionlimit() -- set the max recursion depth for the interpreter
settrace() -- set the global debug tracing function

>>> 

 

 

 

stdin , stdout , 以及stderr 变量包含与标准I/O 流对应的流对象. 如果需要更好地控制输出,而print 不能满足你的要求, 它们就是你所需要的. 你也可以替换它们, 这时候你就可以重定向输出和输入到其它设备( device ), 或者以非标准的方式处理它们.

 1 #!/usr/bin/python
 2 import sys
 3 #print('Hi, %s!' %input('Please enter your name: ')) python3.*版本用input
 4 print('Hi, %s!' %raw_input('Please enter your name: ')) #python2.*版本用raw_input
 5 运行结果:
 6 Please enter your name: er
 7 Hi, er!
 8 等同于:
 9  #!/usr/bin/python
10 import sys
11 print('Please enter your name:')
12 name=sys.stdin.readline()[:-1]
13 print('Hi, %s!' %name)
14 标准输出
15 print('Hello World!\n')
16 等同于:
17  #!/usr/bin/python
18 import sys
19 sys.stdout.write('output resule is good!\n')

 

 

 

posted @ 2018-05-31 12:03  巨兽~墨菲特  阅读(679)  评论(0编辑  收藏  举报