5

背景

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

我曾尝试更改报价,但没有任何效果。

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

4

5 回答 5

7

怎么样

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

未验证。

于 2013-03-04T17:29:59.910 回答
3

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

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
于 2013-03-04T17:28:48.640 回答
1

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

import os

然后,他们需要说他们想列出所有内容。在此范围内,他们需要确保打印输出。

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

这就是我能够解决它的方法。多亏了这一点。

于 2013-03-04T21:30:52.380 回答
1

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

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

但是,如果您要获取目录列表,请使用模块中可用的功能使其独立于操作系统,os例如os.listdir()os.chdir()

于 2013-03-04T17:24:39.120 回答
-1

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

import subprocess
subprocess.call("cmd /c dir /s")
于 2013-03-04T17:29:47.630 回答