xxm*_*exx 4 python windows subprocess python-2.7
背景
我一直dir/s在批处理文件中使用该命令.但是,我无法使用python调用它.注意:我使用的是Python 2.7.3.
码
import subprocess
subprocess.call(["dir/s"])
Run Code Online (Sandbox Code Playgroud)
错误信息
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
Run Code Online (Sandbox Code Playgroud)
我试过改变报价但没有任何效果.
我该如何dir/s使用模块subprocess?
怎么样
subprocess.call("dir/s", shell=True)
Run Code Online (Sandbox Code Playgroud)
未验证.
dir和之间需要有一个空格/s。因此将其分解为一个包含 2 个元素的数组。另外,正如 carlosdoc 指出的那样,您需要添加 shell=True,因为该dir命令是 shell 内置命令。
import subprocess
subprocess.call(["dir", "/s"], shell=True)
Run Code Online (Sandbox Code Playgroud)
但是,如果您尝试获取目录列表,请使用模块中可用的功能使其独立于操作系统,os例如os.listdir(),os.chdir()