Windows XP - Environment variable - Unicode

Alan Kennedy alanmk at hotmail.com
Fri Jul 11 06:06:49 EDT 2003


sebastien.hugues wrote:
> I would like to retrieve the application data directory path of the
> logged user on windows XP. To achieve this goal i use the
> environment variable APPDATA.
> 
> The logged user has this name: sébastien.
> I would like to first decode this string and then re-encode it in
> utf-8, but i am not able to find out what encoding is used when i
> make:
> 
> appdata = os.environ ['APPDATA']
> 
> Any ideas ?

Are you setting the environment at a windows command prompt, i.e.
under cmd.exe? If yes, then type following command to find out what
character set encoding is in use in that terminal:

chcp

Most likely it will be "cp850", i.e. "Code page 850". Assuming that
"chcp" does report "cp850", then this code should achieve what you
need (tested on Win2k only, not XP, but should be same)

C:\>set APPDATA="sébastien"
C:\>python
Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> username = os.environ['APPDATA'].decode('cp850')
>>> username
u'"s\xdabastien"'
>>>

Of course, you will get a "UnicodeError: ASCII encoding error: ordinal
not in range(128)" if you try to print that, but it should be usable
for making up filenames.

Of course, this may not work if the APPDATA environment variable is
set outside a command window. If, for example, it was set through the
control panel, then it should be in the system default encoding. But
we'll cross that bridge when we come to it.

Note also that "chcp" stands for "change code page", meaning that you
can change the character set used by the terminal. A list of character
sets supported can be found here:

http://www.microsoft.com/globaldev/reference/wincp.mspx

Let us know if that works.

-- 
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