0

I know that print writes decoded string on stdout, something like this in Python:

>>> def alt_print(*arg):
...     [x.decode(sys.stdin.encoding).encode(sys.stdout.encoding) for x in arg]
...     sys.stdout.write(''.join(arg) + '\n') if len(arg) < 2 else sys.stdout.write(str(arg) + '\n')

But it's still hard to understand how does input function actually capture data?

Does it use different process to first print the string and then while loop on another process to listen to the stdin?

Note: I couldn't find answer of this on stackoverflow, my question is how does input specifically works!

ShellRox
  • 2,532
  • 6
  • 42
  • 90
  • the code you posted doesn't seem to read `stdin` at all. What's the relation with `input()` ? – Jean-François Fabre Mar 02 '17 at 09:11
  • +Jean-Francois Fabre Sorry i compared print function to input function if it has any common. – ShellRox Mar 02 '17 at 09:12
  • @Jean-FrançoisFabre - I think it's just a demo of `sys.stdout`. – TigerhawkT3 Mar 02 '17 at 09:12
  • not my downvote BTW... – Jean-François Fabre Mar 02 '17 at 09:12
  • 1
    From the source code: *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.* – cdarke Mar 02 '17 at 09:15
  • The C implementation is in function `builtin_input_impl` in `Python/bltinmodule.c` – cdarke Mar 02 '17 at 09:18
  • @cdarke Does it use different processes to print the string and listen to stdin? – ShellRox Mar 02 '17 at 09:20
  • @ShellRox, no, everything is done inside one process - the python process. Why would you think otherwise? The sequence is straightforward, write the prompt to stdout (file descriptor 0) *then* read from stdin (file descriptor 1). – cdarke Mar 02 '17 at 14:11
  • @cdarke I thought it used different processes to print string and listen to stdin for some reason, and does it use while loop to wait and listen to input? and does it use stdin log file to capture the input? – ShellRox Mar 02 '17 at 16:10
  • It does not use a while loop, it is known as a *blocking* call. The process will block until there is data to be read. I have no idea what you mean by "stdin log". Which operating system are you using? – cdarke Mar 03 '17 at 20:59
  • @cdarke I am using Mac OS X, with stdin log i mean `sys.stdin.readlines()` – ShellRox Mar 05 '17 at 07:24

0 Answers0