为什么我的python子流程代码无法正常工作? [英] Why won't my python subprocess code work?
问题描述
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!
推荐答案
您似乎想存储来自subprocess.Popen()
调用的输出.
有关更多信息,请参见子进程-Popen.communicate(input=None)
.
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
[..]
但是Windows shell(cmd.exe)没有ls
命令,但是还有其他两种选择:
However Windows shell (cmd.exe) doesn't have a ls
command, but there's two other alternatives:
使用os.listdir()
-这应该是首选方法,因为使用起来更容易:
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']
使用Powershell -默认安装在较新版本的Windows(> = Windows 7)上:
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
[..]
使用cmd.exe的Shell命令将如下所示:
Shell commands using cmd.exe would be something like this:
test = subprocess.Popen(['cmd', '/C', 'ipconfig'], stdout=subprocess.PIPE)
有关更多信息,请参见:
永远有用且整洁的子流程模块-在终端模拟器-Windows
For more information see:
The ever useful and neat subprocess module - Launch commands in a terminal emulator - Windows
注释:
- 请勿使用
shell=True
,因为这会带来安全风险.
有关更多信息,请参见为什么不只是使用在subprocess.Popen中使用Python? - 请勿使用
from module import *
.在您不应该使用的语言构造中查看原因br> 当您使用subprocess.Popen()
时,它甚至在这里都没有用.
- Do not use
shell=True
as it is a security risk.
For more information see Why not just useshell=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 usesubprocess.Popen()
.
这篇关于为什么我的python子流程代码无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!