how to get output.

Peter Otten __peter__ at web.de
Thu Aug 9 04:21:39 EDT 2007


 indu_shreenath at yahoo.co.in wrote:

> I corrected a typ below.
> 
> On Aug 9, 12:50 pm, indu_shreen... at yahoo.co.in wrote:
>> Hey,
>>
>> I did write the following:
>> but it does not work.
>>
>> import subprocess as sp
>> try:
>>     p = sp.Popen("DIR . /AD /B", stdout=sp.PIPE)
>>     result = p.communicate()[0]
>>     print result
>>  except:
>>      print "error"
>>
>> This throws error.
>> DIR . /AD /B will list out only directories in the current directory.

try:
    ...
except:
    print "error"

is a really bad idea because it hides any meaningful and therefore valuable
information about the error.

IIRC the "dir" command is internal to the dos shell and therefore has to be
called indirectly. The actual command is "cmd", not "dir":

[following snippet found at
http://www.python-forum.de/viewtopic.php?p=73048&sid=13808229538bd52de4ef75c32cf67856]

>>> import subprocess 
>>> args = ["cmd", "/C", "dir", "J:\\", "/O", "/AD", "/B"] 
>>> process = subprocess.Popen(args, stdout = subprocess.PIPE, stderr =
subprocess.STDOUT) 
>>> print process.stdout.read() 

If you just want a list of subdirectories, here's a better approach:

>>> def directories(folder):
...     return os.walk(folder).next()[1]
>>> directories(".")
[snip list of subdirectories of cwd]

Peter



More information about the Python-list mailing list