commands.getstatusoutput on NT

David Bolen db3l at fitlinxx.com
Wed May 24 18:03:47 EDT 2000


"Lee, Jaeho" <Jhlee at Brooks.com> writes:

> I want to use commands.getstatusoutput on NT. I have some python script
> works on Unix and I want to port it to NT. Except getstatusoutput,
> everything is working fine. I made a simple test script.
> 
> import commands
> r = commands.getstatusoutput("dir")
> for s in r:
>     print s
> 
> But r has the following error message.
> 
> 1
> The name specified is not recognized as an
> internal or external command, operable program or batch file.
> 
> What did I do wrong? On Unix, commands.getstatusoutput("ls") works fine. If
> there is any other method that does same job on NT, I can change my script.
> What I want to do is run shell command and get the result.

The problem is that the commands module is Unix-specific.  In this
case, getstatusoutput is doing an os.popen on a string of the form
"{ cmd; } 2>&1", which won't work under NT.  I think the commands
module is documented in the Unix-specific chapter of the library
documentation (the module source also has a comment to that effect).

If you want to execute a command and get its output more portably,
you could probably just do the os.popen() call yourself,
conditionalizing the actual command more precisely than
commands.getstatusoutput permits.  Since you've already got to
conditionalize ls versus dir somehow that shouldn't introduce too much
more complexity in terms of OS-handling.  If you peek at the module,
you'll see that the source for commands.getstatusoutput is pretty simple.

For example, the command:

    s,r = commands.getstatusoutput("dir")

could be replaced with:

    pipe = os.popen("dir 2>&1")
    r = pipe.read()
    s = pipe.status()

where r is the output and s the status (None if no error).  I didn't
bother simulating handling the return as a single list (as you have
when you just set it to r).  You may or may not need the 2>&1, but
without it, the pipe will only return stdout from the child process.

It may be worth pointing out however, that while this can be a good
approach for arbitrary commands, in the particular case of a directory
listing (e.g., "ls" versus "dir") you may be better served - and more
portably - by using some other functions in the os module such as
os.listdir(), perhaps coupled with os.stat() to individual file
details.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list