Reputation: 1
I'm trying to get what is currently in the console window in a Python script.
For example;
print('Bar')
print('Foo')
print('\n')
print([variable I'm asking for])
Expected outcome:
Bar
Foo
Bar
Foo
But also:
os.system('dir')
print([the variable I'm asking for])
with the expected outcome:
[directories]
[directories]
I've tried the following (from in python, get the output of system command as a string):
import subprocess
print('test1')
print('test2\n')
proc = subprocess.Popen('ls', stdout=subprocess.PIPE, shell=True)
cmdstr = proc.stdout.read()
print(cmdstr)
and expected something like this:
test1
test2
test1
test2
but I got this:
test1
test2
'ls' is not recognized as an internal or external command,
operable program or batch file.
b''
I've found this somewhere:
import sys
from io import StringIO
sys.stdout = temporarystd = StringIO() # redirect stdout
# stuff here
sys.stdout = sys.__stdout__ # return stdout to its old state
print(temporarystd.getvalue())
This worked fine for print()
but I try to use os commands and those still go to the terminal.
Anyone knows why?
(Also, as mentioned by @dump-eldor; 'ls'
in proc = subprocess.Popen('ls', stdout=subprocess.PIPE, shell=True)
should've been 'dir'
.)
Upvotes: 0
Views: 157
Reputation: 136
it looks like you run the program from windows os?if so try "dir" instead of "ls"
Upvotes: 1