How to use the dir/s command in Python?

2019-02-18 14:47发布

Background

I use the command dir/s in batch files all the time. But, I am unable to call this using python. NOTE: I am using Python 2.7.3.

Code

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

Error Message

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

I have tried changing the quotations but nothing has worked.

How would I call the dir/s module using subprocess?

5条回答
我只想做你的唯一
2楼-- · 2019-02-18 15:32

I finally found the answer. To list all directories in a directory (e.g. D:\\, C:\\) on needs to first import the os module.

import os

Then, they need to say that they want to list everything. Within that, they need to make sure that the output is printed.

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

That was how I was able to solve it. Thanks to this.

查看更多
乱世女痞
3楼-- · 2019-02-18 15:33

You need a space between dir and /s. So break it into an array of 2 elements. Also as carlosdoc pointed out, you would need to add shell=True, since the dir command is a shell builtin.

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

But if you're trying to get a directory listing, make it OS independent by using the functions available in the os module such as os.listdir(), os.chdir()

查看更多
Emotional °昔
4楼-- · 2019-02-18 15:36

This is a lot different than what you're asking but it solves the same problem. Additionally, it solves it in a pythonic, multiplatform way:

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
查看更多
Anthone
5楼-- · 2019-02-18 15:38

As it's an inbuilt part of the command line you need to run it as:

import subprocess
subprocess.call("cmd /c dir /s")
查看更多
聊天终结者
6楼-- · 2019-02-18 15:39

How about

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

Not verified.

查看更多
登录 后发表回答