I just want to use os.system("dir") and also be able to save the text outputted to a variable. I tried using sys.stdout.read()
but running sys.stdout.readable()
returns False
. Do you know how I can read from the terminal?

- 43
- 6
-
Have a read of https://stackoverflow.com/a/70833/2299087 – James McPherson Jun 02 '20 at 01:12
-
Did you want `sys.stdin` instead? – Mad Physicist Jun 02 '20 at 01:19
4 Answers
You can use the subprocess.check_output method
Example
import subprocess as sp
stdout = sp.check_output("dir")
print(stdout)

- 844
- 6
- 13
There is a bit of confusion here about the different streams, and possibly a better way to do things.
For the specific case of dir
, you can replace the functionality you want with the os.listdir
function, or better yet os.scandir
.
For the more general case, you will not be able to read an arbitrary stdout
stream. If you want to do that, you'll have to set up a subprocess
whose I/O streams you control. This is not much more complicated than using os.system
. you can use subprocess.run
, for example:
content = subprocess.run("dir", stdout=subprocess.PIPE, check=True).stdout
The object returned by run
has a stdout
attribute that contains everything you need.

- 107,652
- 25
- 181
- 264
If you want to read just go with
x = input()
This reads a one line from the terminal. x
is a string by default, but you can cast it, say to int, like so
x = int(x)

- 1,557
- 1
- 10
- 22