How is the bottom layer of print and the bottom layer of input implemented?

print()

Let ’s talk about print () using sys.stdout.write () in advance ...

description

The print () method is used to print out the most common function.

Added the flush keyword parameter in Python 3.3.

print 在 Python3.x 是一个函数,但在 Python2.x 版本不是一个函数,只是一个关键字。

grammar

Following is the syntax of print () method:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
参数

objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
sep -- 用来间隔多个对象,默认值是一个空格。
end -- 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
file -- 要写入的文件对象。
flush -- 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。

return value

no.

Next, let's see how he wrote the bottom layer.

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    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.
    flush: whether to forcibly flush the stream.
    """
    pass

We can see this sentence:Prints the values to a stream, or to sys.stdout by default.

  • Translation: Print the value to the stream or sys. stdout by default

Let's look at the bottom of stdout in sys

stdout = None # (!) forward: __stdout__, real value is "<_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp1252'>"

We can see that mode represents writing 'w', which is write

Then we look at what parameters can sys.stdont accept?

print(dir(sys.stdout))

hello['_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', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 
'write' # look here
, 'write_through', 'writelines']

We saw that there is a write method.

  • test:

    import sys
     
    print('hello')
    sys.stdout.write('hello')
    print('new')
     	 
    # 结果:
    # hello
    # hellonew
    

At this point, you can see that sys.stdout.write also prints out the data.

So print () is implemented with sys.stdout.write ()

But you can still see that the two are still different.

  • There is no line break at the end of sys.stdout.write (), and print () is line break. In addition, write () only accepts parameters in string format.

  • print () can receive multiple parameter outputs, write () can only receive one parameter.

Remember the sentence at the bottom of the print just now: end: string appended after the last value, default a newline.

  • Translation: End: The string after the last value, the default is a line break.

Now that we are all here, everyone will definitely ask what the flash parameter is just now?

  • flush-Whether the output is cached usually depends on the file, but if the flush keyword parameter is True, the stream will be forced to be flushed.

Use the flush parameter to generate a loading effect:

import time

print("---RUNOOB EXAMPLE : Loading 效果---")

print("Loading",end = "")
for i in range(20):
    print(".",end = '',flush = True)
    time.sleep(0.5)

Effect picture:
Insert picture description here



input()

Let me start by saying that input () in Python3 is implemented with sys.stdin.readline (). Wiring to explain

  • The input () function in Python 3.x accepts a standard input data and returns it as a string type.

  • In Python2.x, input () is equal to eval (raw_input (prompt)), which is used to get the input of the console.

raw_input () treats all inputs as strings and returns the string type. And input () has its own characteristics when dealing with pure digital input. It returns the type of the input number (int, float).

注意:input()raw_input() 这两个函数均能接收 字符串 ,
但 raw_input() 直接读取控制台的输入(任何类型的输入它都可以接收)。
而对于 input() ,它希望能够读取一个合法的 python 表达式,
即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。

除非对 input() 有特别需要,否则一般情况下我们都是推荐使用 raw_input() 来与用户交互。

注意:python3 里 input() 默认接收到的是 str 类型。

Function syntax

input([prompt])

Parameter Description:

prompt: prompt message

Let's take a look at the underlying writing of input ():

def input(*args, **kwargs): # real signature unknown
    """
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
    """
    pass

Look at this sentence in the note On *nix systems, readline is used if available.

  • Translation: On * nix system, use readline if available.

\*nix 就是unix 操作系统和 linux操作系统。就是说只要你的操作系统是Unix或者linux,无论哪个开发商或者版本,就是属于*nix。
这种命名方式主要是用于软件兼容性说明或者网络建站上传服务器文件时需要确认的信息。

所以 input 是 sys.readline()实现的?
no no no...

大家都知道 readline()是读一行,可是 读谁呢?

Everything you enter in the computer is to be entered through the keyboard, so
at this time there will be a function (method) stdin that monitors keyboard input

stdin是标准输入,一般指键盘输入到缓冲区里的东西。

# sys 支持的所有方法
print(dir(sys))

['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_framework', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'breakpointhook', '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_origin_tracking_depth', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 
'stderr', 'stdin', # look here
'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']
sys.stdin 底层源码:

stdin = None # (!) real value is "<_io.TextIOWrapper name=3 mode='r' encoding='cp1252'>"

Everyone sees that the type of mode is read 'r', take a look at the methods supported by sys.stdin

print(dir(sys.sdtin))

['_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', # 我们在这里
'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines']

The input () in Python3 is implemented with sys.stdin.readline ().

import sys
 
a = sys.stdin.readline()
print(a, len(a))
 
b = input()
print(b, len(b))
 
 
# 结果:
# hello
# hello
#  6
# hello
# hello 5
  • readline () will also include the newline at the end.

  • Readline () can be given integer parameters, which means to get a few bits from the current position. When the given value is less than 0, the end of this line is always obtained.

import sys
 
a = sys.stdin.readline(3)
print(a, len(a))
 
# 结果:
# hello
# hel 3

readline () If the result of the integer parameter is given and the line is not read, the next readline () will continue to read from the end of the last time, the same as reading the file.

import sys
 
a = sys.stdin.readline(3)
print(a, len(a))
 
b = sys.stdin.readline(3)
print(b, len(b))
 
# 结果
# abcde
# abc 3
# de
#  3

input () can receive string parameters as input prompts, readline () does not have this function.

Reference original site: https://blog.csdn.net/lnotime/article/details/81385646
Reference original site rookie tutorial: https://www.runoob.com/python/python-func-input.html



I really hope that CSDN can introduce the function of code scaling. These low-level source code displays take up too much screen space.

Published 128 original articles · Like 261 · Visits 120,000+

Guess you like

Origin blog.csdn.net/weixin_44685869/article/details/105609007