2

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()
5
  • Why don't you use input() ? Commented Jun 13, 2020 at 9:56
  • To speed up the program. Commented Jun 13, 2020 at 12:57
  • 0x5961736972: can you please provide a source backing your statment? AFAIK input() doesn't slow your script. Commented Jun 13, 2020 at 14:22
  • stackoverflow.com/q/3857052/13597101 Commented Jun 14, 2020 at 7:14
  • The question that you linked is unrelated to input slowering your script, it actually talks about output. I won't post any further comments here, but I definitely advise you to read about python's build-in input function because you've a misconception about what it does and doesn't. Commented Jun 14, 2020 at 11:44

1 Answer 1

5

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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.