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.
-
1What 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](https://stackoverflow.com/help) and read on [how to ask](https://stackoverflow.com/help/asking). 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](https://stackoverflow.com/posts/57145550/edit) it – Tomerikoo Jul 22 '19 at 11:59
-
I don't get what's unclear about this question. – Riedler Jul 22 '19 at 12:01
-
I meant reading from the same place that print() writes to. sys.stdout doesn't have a read function. – Riedler Jul 22 '19 at 12:03
-
1you mean [`input()`](https://docs.python.org/3/library/functions.html#input)? And sorry, maybe it's just me, but that question is very unclear... could be interpreted in many ways – Tomerikoo Jul 22 '19 at 12:04
-
No, input() reads user input, but I want to get text that's already been written before the function gets called. – Riedler Jul 22 '19 at 12:06
-
1There you have it. Quick google search – Tomerikoo Jul 22 '19 at 12:10
-
Sorry, that's it, I just couldn't find it. Thanks for finding. – Riedler Jul 22 '19 at 12:19
2 Answers
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
.

- 2,889
- 1
- 13
- 26