Why won't my python subprocess code work? [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-08 12:18:18

问题


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!


回答1:


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)

For more information see:
The ever useful and neat subprocess module - Launch commands in a terminal emulator - Windows


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().



回答2:


A agree with timss; Windows has no ls command. If you want a directory listing like ls on Windows use dir /B for single-column or dir /w /B for multi-column. Or just use os.listdir. If you do use dir, you must start subprocess using subprocess.Popen(['dir', '/b'], shell=True). If you want to store the output, use subprocess.Popen(['dir', '/b'], shell=True, stdout=subprocess.PIPE). And, the reason I used shell=True is that, since dir is an internal DOS command, the shell must be used to call it. The /b strips the header, and the /w forces multi-column output.



来源:https://stackoverflow.com/questions/16544362/why-wont-my-python-subprocess-code-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!