如何在Python中使用dir / s命令?

背景

我一直在batch file中使用命令dir/s 。 但是,我无法使用python来调用它。 注意:我正在使用Python 2.7.3。

 import subprocess subprocess.call(["dir/s"]) 

错误信息

 Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> subprocess.call(["dir/s"]) File "C:\Python27\lib\subprocess.py", line 493, in call return Popen(*popenargs, **kwargs).wait() File "C:\Python27\lib\subprocess.py", line 679, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 896, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified 

我试图改变报价,但没有任何工作。

我将如何使用subprocess调用dir/s模块?

怎么样

 subprocess.call("dir/s", shell=True) 

未经审核的。

这与你所要求的有很大不同,但它解决了同样的问题。 此外,它以pythonic,多平台的方式解决它:

 import fnmatch import os def recglob(directory, ext): l = [] for root, dirnames, filenames in os.walk(directory): for filename in fnmatch.filter(filenames, ext): l.append(os.path.join(root, filename)) return l 

dir/s之间需要一个空格。 所以把它分解成2个元素的数组。 同样carlosdoc指出,你需要添加shell = True,因为dir命令是一个shell内置。

 import subprocess subprocess.call(["dir", "/s"], shell=True) 

但是如果你想获得一个目录列表,通过使用os模块中可用的函数os.listdir()os.listdir()os.chdir()

我终于找到了答案。 要列出目录中的所有目录(例如D:\\C:\\ ),需要先导入os模块。

 import os 

然后,他们需要说,他们要列出一切。 其中,他们需要确保输出结果是打印的。

 for top, dirs, files in os.walk('D:\\'): for nm in files: print os.path.join(top, nm) 

我就是这样解决的。 感谢这一点。

由于它是命令行的内置部分,因此需要将其运行为:

 import subprocess subprocess.call("cmd /c dir /s")