1

I'm trying to get a already written line in python 3, but I haven't found any function that can read a line from the terminal. It should work something like sys.stdout.read(), or sys.stdout.readline() but this function just throws an error.

7
  • 1
    What do you mean by read a line from the terminal? Run the program with sys arguments? input something to the program? read from the terminal's history? Please refer to the help center and read on how to ask. In this question it is both unclear what you are asking and sounds too broad and is likely to get closed if you don't edit it Commented Jul 22, 2019 at 11:59
  • I don't get what's unclear about this question. Commented Jul 22, 2019 at 12:01
  • I meant reading from the same place that print() writes to. sys.stdout doesn't have a read function. Commented Jul 22, 2019 at 12:03
  • 1
    you mean input()? And sorry, maybe it's just me, but that question is very unclear... could be interpreted in many ways Commented Jul 22, 2019 at 12:04
  • 1
    There you have it. Quick google search Commented Jul 22, 2019 at 12:10

2 Answers 2

1

If you mean to read from the user/a pipe, then simply use input.

However, from your comments it seems like you want to be able to read from what has already been printed.

To do this, you have a few options. If you don't actually want it to display on the terminal, and you only care about certain part of the output, then you can use contextlib.redirect_stdout and contextlib.redirect_stderr. You can combine this with io.StringIO to capture the output of your application to a string. This has been discussed in the question Capture stdout from a script in Python

However, if you want to have something which provides you both a means of printing to the terminal and giving you the lines, then you will need to implement your own type which inherits from io.TextIOBase or uses io.TextIOWrapper.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that's pretty much excactly what I asked for.
0

Do you mean something like this?

name = input("Enter a name: ") print(name) 

1 Comment

No, that would read user input, not terminal output.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.