2

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?

4 Answers4

1

You can use the subprocess.check_output method

Example

import subprocess as sp

stdout = sp.check_output("dir")
print(stdout)
Sylvaus
  • 844
  • 6
  • 13
1

using os library:

info = os.popen('dir').read()
user3041840
  • 352
  • 4
  • 8
0

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.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

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)
Eeshaan
  • 1,557
  • 1
  • 10
  • 22