[python-win32] regarding invoking command prompt using python

Tim Roberts timr at probo.com
Thu Jun 18 01:19:51 CEST 2009


Vernon Cole wrote:
>
> If I read the request correctly, this question is about how to set
> environment variables from a python script.
> In other words: what is the Python equivalent of the DOS command:
> SET envrmnt="This is the new value"

Well, his question was a bit different, but this is part of it.


> If my experience is correct (I would love it if someone will tell me
> that I am wrong) it cannot be done.

You are correct.  It cannot be done, either on Linux or on Windows.  You
cannot affect the environment of your parent process.


> There MUST be some api to actually do what a SET command does,
> otherwise the CMD shell itself could not do it, but I have never seen
> any documentation for it. This seem to me to be the only thing which
> keeps one from running Python as a command shell.

If you go look for SET.EXE, you won't find it.  It's not a separate
command-line tool -- it is a built-in that CMD processes on its own. 
When you type commands at a command line, you are actually communicating
with the CMD.EXE program itself.  Before it goes to look for an
executable file to run, it checks to see if the command is in its list
of built-ins.  The "if" and "for" commands are also built-ins.

That's why the "set" command can change the environment of the cmd.exe
process -- it's being handled by that process.

However, this does not prevent running Python as a command shell.  There
is a perfectly viable Python command shell for DOS called iPython.  It
implements its "set" command in exactly the same way -- it's an internal
command that alters the state of the iPython process, and hence every
process that it spawns.


> The only way I know to permanently set environment variables is:
> -Right-click on "My Computer"
> -select "Properties"
> -select "Advanced System Settings"
> -click on "Environment Variables"

Although this is true, the better solution for "a h" is to create a
batch file and run that.  The batch file then runs as its own process,
so that environment changes remain with the process.

-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the python-win32 mailing list