Command shell access within Python
Pierre Rouleau
pieroul at attglobal.net
Sun Nov 4 18:46:25 EST 2001
Janko Hauser wrote:
>
> A better way is to use the commands module. It wraps os.popen and I'm
> not sure if this also didn't open a shell beforehand.
Do you know if the commands module is supported under Win32 (NT) by python 2.1? Or
2.2?
I tried it and without changing the source of commands.py this is the result i get
(under NT):
>>> import commands
>>> dir(commands)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput',
'getstatus', 'getstatusoutput', 'mk2arg', 'mkarg']
>>> (exitstatus, outtext) = commands.getstatusoutput('ls')
>>> exitstatus
1
>>> outtext
'The name specified is not recognized as an\ninternal or external command, operable
program or batch file.'
Now, I looked at the commands.py and getstatusoutput() is:
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
import os
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
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
The {ls;} does not work in the native NT command shell.
So if i modify the source to the following the problem is solved:
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
import os
if os.name in ['nt', 'dos', 'os2'] :
# use Dos style command shell for NT, DOS and OS/2
pipe = os.popen(cmd + ' 2>&1', 'r')
else :
# use Unix style for all others
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
Now it works fine under NT:
>>> reload(commands)
<module 'commands' from 'c:\python21\lib\commands.py'>
>>> (stat, text) = commands.getstatusoutput('ls')
>>> stat
0
>>> print text
calc
freeware
mkssi
mkssi.py
mkssi.pyc
si_localChekpoint.py
testname.py
testname.pyc
testtk.py
testtk.pyc
>>>
So, in the end, it looks like commands could be used under Win32 and DOS-like
command shells.
The docstring in commands.py states that it is for Unix only. Is it worthed to add
Win32 compatibility so that modules using commands.py can run in Win32 as well?
Pierre
More information about the Python-list
mailing list