What does sys.stdin.readline() do?


#1

Hi, this is not my code. I am just wondering why the programmer wrote the first two lines instead of using input()? I understand that he is just assigning the function sys.stdin.readline to the variable input, then calling sys.stdin.readline using input() in line 3, but why go through all that trouble. Why not just use the function input()? I know that the function input() uses sys.stdin.readline() under the hood, but why not just use input()? Thanks.

import sys
input = sys.stdin.readline

curDay, days = map(int, input().split())
curDay -= 1
cur = 1

print('Sun Mon Tue Wed Thr Fri Sat')

for i in range(curDay):
    print('    ', end='')

while True:
    print('%3d' % (cur), end='')
    if cur == days:
        print()
        break
    cur += 1
    curDay += 1
    if curDay == 7:
        curDay = 0
        print()
    else:
        print(" ", end='')

#2

Where did you find this code? Perhaps that page will give us some insight and context.


#3

I found the code on his github page.

The code is for this problem


#4

I had to modify the code slightly to get it to run in Python 3…

import sys
input = sys.stdin.readline

curDay, days = map(lambda x: int(x), input().split())
curDay -= 1
cur = 1

print('Sun Mon Tue Wed Thr Fri Sat')

for i in range(curDay):
    print('    ', end='')

while True:
    print('%3d' % (cur), end='')
    if cur == days:
        print()
        break
    cur += 1
    curDay += 1
    if curDay == 7:
        curDay = 0
        print()
    else:
        print(" ", end='')
================= RESTART: D:/cc/python/calendar_tools_2.py =================
2 31
Sun Mon Tue Wed Thr Fri Sat
      1   2   3   4   5   6
  7   8   9  10  11  12  13
 14  15  16  17  18  19  20
 21  22  23  24  25  26  27
 28  29  30  31
>>> 

It would appear the author is creating his own input function by assigning sys.stdin.readline to that indentifier. But is still returns a string, so I’m not sure this was intended to run in Python 3. Not sure I follow his map() expression but my substitution completes as expected.


#5

Thanks. So much. Could you also explain what’s the difference between input() and sys.stdin.readline() in Python 3. I tried searching online, but I couldn’t understand what was said.Thanks!


#6

This (AMRoche’s reply) is fairly straight forward. I couldn’t explain it any better given my own limitations.

https://github.com/varjmes/noquestionistupid/issues/21