2016-02-05 57 views
0

我想在shell中看到Windows'dir命令的内容。我安装了Cygwin和mingw。有了这个代码,子进程check_output(['dir'])与预期不符

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

它被解析为

DCcircuits.py 
IDLE\ (idle.pyw).lnk 
Newpy.bat 
change\ fileops.readfile\ to\ match\ line\ indent.txt 
chext 
clark\ wifi 
downloading\ again 
drumset\ project 
idle.bat\ -\ Shortcut.lnk 
idle.pyw\ -\ Shortcut.lnk 
indexProgramFiles.py 
maps\ traveler 
orderedDict.txt 
pipfreeze.txt 
remote\ wireless 
searchContents.py 
sleep\ calculator\ project 
tracertIps.py 

我试图像这样显示的输出。

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 
11/03/2015 03:10 PM <DIR>   .eclipse 
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 
03/29/2015 05:49 PM <DIR>   .pdfsam 
01/26/2016 09:47 PM <DIR>   .phet 
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 

当我拿出的Cygwin和MinGW出path,这个错误发生:

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 

有没有办法让我想要的结果,而无需将数据存储在外部文件?

在此先感谢。

回答

1

传递shell=Truecheck_output似乎工作。我怀疑dir是作为shell(cmd)内置而不是独立的可执行文件实现的。

+0

谢谢。它试图执行它,只找到'dir.exe'的cywin版本。现在'shell'修复它。 –

+0

@ClaytonWahlstrom ['dir' cmd的内部命令](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python#comment31032086_89243)和cygwin的'dir'是独立的(但相关:两者显示文件列表)命令。 – jfs