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?

2

4 Answers 4

1

using os library:

info = os.popen('dir').read() 
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the subprocess.check_output method

Example

import subprocess as sp stdout = sp.check_output("dir") print(stdout) 

Comments

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.

Comments

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.