Problem using commands.getoutput()

J

J

Reading up on ways to run commands in a shell and capture output...

So I was looking at os.exec*() and that's not the correct thing here.
If I understand the docs correctly, the os.exec*() functions actually
end the calling program and replace it with the program called by
os.exec*() even as far as giving the new process the calling process's
PID:

"These functions all execute a new program, replacing the current
process; they do not return. On Unix, the new executable is loaded
into the current process, and will have the same process id as the
caller. Errors will be reported as OSError exceptions."

So from there, I found the commands module and getoutput() which
again, if I'm right, is supposed to run a command in a shell, and
return the output of that command a string.

commands.getoutput() is this:

def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
import os
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None: sts = 0
if text[-1:] == '\n': text = text[:-1]
return sts, text

or at least it calls this function, and returns text, ignorint sts...

However, when I try using it, I get this:'{' is not recognized as an internal or external command,
operable program or batch file.
Which looks like it's choking on the format of the "pipe = os.popen"
line, but that's just a guess... because this works:

p = os.popen('dir','r')
p.read()
p.close()

So what's the point of the commands module, or is that one that only
works in Linux, and not Windows? I can do what I want, I think, by
using os.popen(), but I wanted to know if there was a better way of
doing it.

Cheers,
Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top