How to use Subprocess in Windows How to use Subprocess in Windows windows windows

How to use Subprocess in Windows


I think what you are looking for is os.listdir()

check out the os module for more info

an example:

>>> import os>>> l = os.listdir()>>> print (l)['DLLs', 'Doc', 'google-python-exercises', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'tcl', 'Tools', 'VS2010Cmd.lnk']>>>

You could also read the output into a list:

result = []process = subprocess.Popen('dir',     shell=True,     stdout=subprocess.PIPE,     stderr=subprocess.PIPE )for line in process.stdout:    result.append(line)errcode = process.returncodefor line in result:    print(line)


As far as I know, dir is a built in command of the shell in Windows and thus not a file available for execution as a program. Which is probably why subprocess.Popen cannot find it. But you can try adding shell=True to the Popen() construtor call like this:

def runcmd(cmd):    x = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)    return x.communicate(stdout)runcmd("dir")

If shell=True doesn't help, you're out of luck executing dir directly. But then you can make a .bat file and put a call to dir there instead, and then invoke that .bat file from Python instead.

btw also check out the PEP8!

P.S As Mark Ransom pointed out in a comment, you could just use ['cmd', '/c', 'dir'] as the value of cmd instead of the .bat hack if shell=True fails to fix the issue.