from subprocess import *
test = subprocess.Popen('ls')
print test
When i try to run this simple code, I get an error window saying:
WindowsError: [Error 2] The system cannot find the file specified
I have no clue why I can't get this simple code to work and it's frustrating, any help would be greatly appreciated!
解决方案
It looks like you want to store the output from a subprocess.Popen() call.
For more information see Subprocess - Popen.communicate(input=None).
>>> import subprocess
>>> test = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> out, err = test.communicate()
>>> print out
fizzbuzz.py
foo.py
[..]
However Windows shell (cmd.exe) doesn't have a ls command, but there's two other alternatives:
Use os.listdir() - This should be the preffered method since it's much easier to work with:
>>> import os
>>> os.listdir("C:\Python27")
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe
', 'pythonw.exe', 'README.txt', 'tcl', 'Tools', 'w9xpopen.exe']
Use Powershell - Installed by default on newer versions of Windows (>= Windows 7):
>>> import subprocess
>>> test = subprocess.Popen(['powershell', '/C', 'ls'], stdout=subprocess.PIPE)
>>> out, err = test.communicate()
>>> print out
Directory: C:\Python27
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 14.05.2013 16:00 DLLs
d---- 14.05.2013 16:01 Doc
[..]
Shell commands using cmd.exe would be something like this:
test = subprocess.Popen(['cmd', '/C', 'ipconfig'], stdout=subprocess.PIPE)
Notes:
Do not use shell=True as it is a security risk.
For more information see Why not just use shell=True in subprocess.Popen in Python?
Do not use from module import *. See why in Language Constructs You Should Not Use
It doesn't even serve a purpose here, when you use subprocess.Popen().