Wy can't Powershell display a string when i use stdout in Python?

Viewed 260

It runs fine in VS Code, but in powershell it does prompt user input but without displaying the string in "stdout". Here is the sample piece of code:

import sys


def get_int():
    sys.stdout.write("Enter number(s). ")
    return map(int, sys.stdin.readline().strip().split())


def get_float():
    sys.stdout.write("Enter number(s). ")
    return map(float, sys.stdin.readline().strip().split())


def get_list_of_int():
    sys.stdout.write("Enter numbers followed by space. ")
    return list(map(int, sys.stdin.readline().strip().split()))


def get_string():
    sys.stdout.write("Enter string. ")
    return sys.stdin.readline().strip()


a, b, c, d = get_int()
e, f, g = get_float()
arr = get_list_of_int()
str = get_string()
1 Answers

Why can't Powershell display a string when i use stdout in Python?

Because the stdout device interface may buffer writes to it, so either run python in unbuffered mode:

PS C:\> python -u script.py

or explicitly flush the buffer before reading stdin:

def get_int():
    sys.stdout.write("Enter number(s). ")
    sys.stdout.flush()
    return map(int, sys.stdin.readline().strip().split())

or you can replace sys.stdout with a wrapper that does it for you:

class Unbuffered(object):
   def __init__(self, stream):
       self.stream = stream
   def write(self, data):
       self.stream.write(data)
       self.stream.flush()
   def writelines(self, datas):
       self.stream.writelines(datas)
       self.stream.flush()
   def __getattr__(self, attr):
       return getattr(self.stream, attr)

sys.stdout = Unbuffered(sys.stdout)

# this will now flush automatically before calling stdin.readline()
sys.stdout.write("Enter something: ")
numbers = map(int, sys.stdin.readline().strip().split())
Related