2

I want to see the contents of the Windows' dir command in the shell. I have Cygwin and mingw installed. With this code,

import subprocess as sub
print sub.check_output(['dir'])

it gets parsed as

DCcircuits.py
IDLE\ (idle.pyw).lnk
Newpy.bat
idle.bat\ -\ Shortcut.lnk
idle.pyw\ -\ Shortcut.lnk
indexProgramFiles.py
maps\ traveler
orderedDict.txt
pipfreeze.txt
remote\ wireless
tracertIps.py

I am trying to display an output like this.

 Volume in drive C is TI10693600D
 Volume Serial Number is 240D-7F0A

 Directory of C:\Users\Clayton

02/03/2016  10:22 AM    <DIR>          .
02/03/2016  10:22 AM    <DIR>          ..
11/05/2015  03:07 PM    <DIR>          .android
08/14/2015  12:02 PM    <DIR>          .idlerc
11/01/2015  10:38 PM    <DIR>          .jmc
01/04/2016  09:33 AM    <DIR>          .matplotlib
01/08/2016  10:18 AM    <DIR>          .oracle_jre_usage
09/04/2015  02:43 PM    <DIR>          3D Objects
01/29/2016  12:06 PM    <DIR>          Contacts
02/05/2016  10:35 AM    <DIR>          Desktop
02/04/2016  08:38 PM    <DIR>          Documents
02/04/2016  04:31 PM    <DIR>          Downloads
01/29/2016  12:06 PM    <DIR>          Favorites
02/04/2016  05:25 PM    <DIR>          Google Drive
01/29/2016  12:06 PM    <DIR>          Links
01/29/2016  12:06 PM    <DIR>          Music
12/24/2015  03:10 PM    <DIR>          OneDrive
02/03/2016  03:36 PM    <DIR>          Pictures
01/29/2016  12:06 PM    <DIR>          Saved Games
01/29/2016  12:06 PM    <DIR>          Searches
11/28/2014  10:14 PM    <DIR>          Shared
04/12/2015  03:23 PM    <DIR>          Tracing
01/29/2016  12:06 PM    <DIR>          Videos
               0 File(s)              0 bytes
              26 Dir(s)  480,478,224,384 bytes free

When I take out cygwin and mingw out of path, this error happens:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\subprocess.py", line 566, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "C:\Python27\lib\subprocess.py", line 710, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

Is there a way to use CMD instead of Cygwin commands?

Thanks in advance.

cwahls
  • 743
  • 7
  • 22

1 Answers1

3

Passing shell=True to check_output seems to work. I suspect that dir is implemented as a shell (cmd) builtin rather than an independent executable.

antony
  • 2,877
  • 4
  • 31
  • 43
  • Thank you. It was trying to execute it and only finding the cywin version of `dir.exe`. Now `shell` fixes it. – cwahls Feb 05 '16 at 22:26
  • 1
    @ClaytonWahlstrom [`dir` cmd's internal command](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python#comment31032086_89243) and cygwin's `dir` are independent (but related: both show a file listing) commands. – jfs Feb 13 '16 at 14:57