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:


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -