I know for many of you that would be easy thing to do, but for me no. So I'm trying to output data from shell, but I'm stucked when I have to transform it into string. I tried with for
, but didn't work. So basically, what I'm trying is: for each new line in my shell, output new line. I'll give an example - the free -m
command. Its output is
total used free shared buffers cached
Mem: 144 512 111 0 0 121
-/+ buffers/cache: 23 232
Swap: 0 0 0
So, what I wrote so far is:
import commands
foo...
sout = commands.getstatusoutput(inp)
return ' '.join(str(line) for line in sout)
foo...
But the output is only one line (the first line - total, used, free, shared etc)
and I want new line for each new line like the output in the shell. If I leave it without .join it outputs something like
(0, ' total used free shared buffers cached\nMem: 512 144 368 0 0 121\n-/+ buffers/cache: 21 234\nSwap: 0 0 0')
and since I want it to be a string, I even tried '\\n'.join
, but it outputed only 0
(wtf). Any ideas?
You could also use os.popen which is much more convenient.
print os.popen('free -m').read()
You might want to read this thread to acquire a good overview of the options available to run shell commands from within python Calling an external command in Python
The entire string is in the tuple, with line breaks and everything, so I suppose all you need to do is:
print sout[1]
Assuming that sout
is the tuple you show in your question:
(0, ' total used free shared buffers cached\nMem: 512 144 368 0 0 121\n-/+ buffers/cache: 21 234\nSwap: 0 0 0')
just make a check for newline character and then insert a new line character in your output. here actually you getting input as a whole. hope it helps
There is another way you can get the same result:
from subprocess import Popen, PIPE
// Create a subprocess and then interact with the process by reading data from
// stdout, untill the end-of-file is reached. Since communicate return tuple
// in the form of stdout, stderr), Capture only the output.
(result, errcode) = Popen('free -m', stdout = PIPE, shell = True).communicate()
print result
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.