import os
import subprocess
p = subprocess.Popen(['cmd', '/v:on', '/q', '/c', 'env.bat', '&echo(!USERNAME!&echo(!PASSWORD!'], stdout=subprocess.PIPE, universal_newlines=True)
stdout, stderr = p.communicate()
username, password = stdout.splitlines()
print(username)
print(password)
Since env.bat
does not use setlocal
, the environmental variables
will be available in the same process of cmd
, after env.bat
is run.
This allows echo
the values of !USERNAME!
and !PASSWORD!
to the
stdout stream.
Options of cmd
:
/v:on
enables delayed expansion.
/q
sets echo off.
/c
runs the following command string.
Note:
Tested in Python 2 and Python 3. Python 2 is missing support for a
context manager with subprocess
so a with
statement was not used.
The USERNAME
environmental variable is a builtin name.
Changing it without good reason may create unexpected issues.
As delayed expansion is enabled, use of !
in env.bat
may need
to be escaped, else !
may be omitted when cmd
parses the file.
call echo
in the command line could avoid the enabling of delayed
expansion if needed.