子流程check_output(['dir'])不符合预期

时间:2016-02-05 18:58:29

标签: python windows python-2.7 format subprocess

我希望在shell中看到Windows“dir命令的内容。我安装了Cygwin和mingw。使用此代码,

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

当我从path中取出cygwin并mingw时,会发生以下错误:

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 个答案:

答案 0 :(得分:2)

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