Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Subprocess in Windows

I am trying to save the result or function runcmd in the variable Result. Here is what I have tried: import subprocess

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

When I run ths code, I get this result:

Traceback (most recent call last):
  File "C:\Python27\MyPython\MyCode.py", line 7, in <module>
    runcmd("dir")
  File "C:\Python27\MyPython\MyCode.py", line 4, in runcmd
    x = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 893, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

What could I do to fix this?

like image 724
AHuman Avatar asked Nov 06 '13 18:11

AHuman


2 Answers

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.e
xe', '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.returncode
for line in result:
    print(line)
like image 84
Chad Dienhart Avatar answered Oct 05 '22 11:10

Chad Dienhart


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.

like image 32
Erik Kaplun Avatar answered Oct 05 '22 11:10

Erik Kaplun