问题
any idea what is the error trying to say?
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
subprocess.call(["ls", "-l"])
File "D:\Python27\lib\subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "D:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite)
File "D:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
回答1:
You are calling the ls
command on windows, which doesn't have an ls
. You can grab a port of ls
for windows from http://gnuwin32.sourceforge.net/packages/coreutils.htm and add it's installed bin dir to your windows PATH
(or add it to PATH at run time of your python script. if you dont know how to to do this, see this and this question respectively).
dir
is the windows equivalent, but it will print differently formatted output compared to ls
, and presumably, this call is to get some kind of information from a directory. There are better ways to do this in python. If you can identify what information it is trying to get (e.g. permission bits), then you might be able to write a pure python version of this (or find an equivalent python snippet for windows that does this) and not rely on external commands.
Interestingly, subprocess.call()
simply runs the command and returns the error code. ls
itself just prints information, so if that is the intent (just to show the user a directory's contents in a console), then you can replace it with a call to dir
. Sometimes, you will need to provide shell=True
as a parameter depending on the command you are calling. Pay attention to the warning in the documentation though. If it is trying to extract information, it probably wants to do a subprocess.Popen()
or subprocress.check_output()
style call, where you actually can consume the called program's output.
If for example, it is just to get the list of files/directories in a directory and/or their timestamps, then this is a very round-about way of getting this information, and they can all be done in python itself e.g. os.walk(), os.fstat(), and in Python3, pathlib are some ways to get file information in a directory.
回答2:
You're trying to execute the ls -l
command on Windows. ls
will only work on Unix-based systems.
subprocess.call(["ls", "-l"])
If you're on Windows, try
subprocess.call(["dir"])
instead.
Alternatively, you could try something like Cygwin.
来源:https://stackoverflow.com/questions/25090981/error-during-subprocess-calling-ls