简体   繁体   中英

How do I read from the terminal in Python?

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?

You can use the subprocess.check_output method

Example

import subprocess as sp

stdout = sp.check_output("dir")
print(stdout)

using os library:

info = os.popen('dir').read()

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM