Environment variables - Expand

Alan Kennedy alanmk at hotmail.com
Mon May 12 09:28:11 EDT 2003


Dips wrote:

> For instance, the following command doesn't expand %WINDIR%
> automatically
> file_name = '%WINDIR%\WIN.INI'
> file = os.open(file,'r')

OK, you're describing several different problems here.

If you want to embed the value of a string variable into another string
variable, the python syntax is

string1 = "%s\\WIN.INI" % "C:\\WinNT"

Now, if you want that Windir to be an environment variable, you can do
as follows.

import os
string1 = "%s\\WIN.INI" % os.getenv("WINDIR")

> In actual 'file_name' is fed as command-line argument and so can
> contain any environement variables.

But this is different. If you want to use command line arguments, use
sys.argv. For example

import sys
filename = sys.argv[1]

However, if you are setting the filename parameter using Windows command
shell commands, then all of the relevant environment variable
substitution and expansion should be carried out by the Windows command
shell, and happen before python does anything. For example

SET WINDIR=C:\winnt
python myscript.py %WINDIR%\WIN.INI

In this case, the Windows command shell should substitute the value of
the WINDIR variable *before* it passes the argument to python.

So the first argument will become "C:\winnt\WIN.INI".

So python should see the argument "C:\winnt\WIN.INI", with no
environment variable substition required from you.

HTH,

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan




More information about the Python-list mailing list