windows - Why won't my python subprocess code work? -
this question has answer here:
from subprocess import * test = subprocess.popen('ls') print test
when try run simple code, error window saying:
windowserror: [error 2] system cannot find file specified
i have no clue why can't simple code work , it's frustrating, appreciated!
it looks want store output subprocess.popen()
call.
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 ls
command, there's 2 other alternatives:
use os.listdir()
- should preffered method since it's easier 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 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 this:
test = subprocess.popen(['cmd', '/c', 'ipconfig'], stdout=subprocess.pipe)
for more information see:
the ever useful , neat subprocess module - launch commands in terminal emulator - windows
notes:
- do not use
shell=true
security risk.
more information see why not useshell=true
in subprocess.popen in python? - do not use
from module import *
. see why in language constructs should not use
doesn't serve purpose here, when usesubprocess.popen()
.
Comments
Post a Comment