Skip to content

Instantly share code, notes, and snippets.

@stania
Last active June 11, 2016 21:45
Show Gist options
  • Save stania/4729409 to your computer and use it in GitHub Desktop.
Save stania/4729409 to your computer and use it in GitHub Desktop.
python implementation replacing "call vsvars32.bat"
from subprocess import Popen
import os, subprocess
def parseEnv(envoutput):
handle_line = lambda l: tuple(l.rstrip().split("=", 1))
pairs = map(handle_line, envoutput)
valid_pairs = filter(lambda x: len(x) == 2, pairs)
valid_pairs = [(x[0].upper(), x[1]) for x in valid_pairs]
return dict(valid_pairs)
def overrideEnv(newenv):
old = os.environ.copy()
removed = set(old) - set(newenv)
for k in newenv.keys():
os.environ[k] = newenv[k]
for k in removed:
os.environ.pop(k)
return old
def setupVSEnv(vsver):
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
cmd = r'cmd /s /c ""%VS{vsver}COMNTOOLS%vsvars32.bat" & set"'.format(**locals())
ret = Popen(cmd, startupinfo=si,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE)
output = ret.communicate()[0]
output = output.split("\r\n")
old = overrideEnv(parseEnv(output))
return old
@fstanley
Copy link

Thanks, this saved me an afternoon

@sanyer
Copy link

sanyer commented Jun 26, 2015

Nice, thanks.

I also refactored it a little bit:

import os
import subprocess as sub


def vs_env_dict(vsver):
    cmd = r'cmd /s /c ""%VS{0}COMNTOOLS%vsvars32.bat" & set"'.format(vsver)
    output = sub.Popen(cmd, stdout=sub.PIPE, stderr=sub.STDOUT, stdin=sub.PIPE).communicate()[0].split("\r\n")

    return dict((e[0].upper(), e[1]) for e in [p.rstrip().split("=", 1) for p in output] if len(e) == 2)

os.environ.update(vs_env_dict(100))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment