[Tutor] Noob to Python - Need help with Variables
Gonçalo Rodrigues
op73418@mail.telepac.pt
Thu Jun 5 07:58:02 2003
----- Original Message -----
From: "Tony Stevenson" <Tony@pc-tony.com>
> Hi All,
>
> I am completely new to programming, so I thought I would start with Python
> as it comes highly reccomended, and have seen it do some very smart
> things.
>
> Anyway, I am trying to re-write our somewhat painful DOS Batch File
> Logon Scripts.
>
> I am currently using print os.environ["USERNAME"] to obtain the
> username environment variable.
>
> Now I will be using this entry several times throughout the script, so I
> "thought" I would need to create a variable in python. But after trying
> this
>
> >>> user = "print os.environ['USERNAME']"
> >>> print user
>
> This is what is returned....
>
>
> print os.environ['USERNAME']
>
Of course. Python does not have telepathic abilities, so if you want that
string to be executed as Python code, be explicit, ask for it:
>>> exec user
But don't -- see below.
>
>
> So I can see that the "variable"??? user, it not executing the print
> os.environ command. Instead is it using it as a text entry.
>
You are thinking in utterly unpythonic terms - may I suggest that you take a
look at the Python tutorial and then, maybe, at some source code? Why the
extra level of indirection? Why not just
>>> user = os.environ['USERNAME']
and now user contains whatever it is that that the environment variable
USERNAME contains?
HTH, with my best regards,
G. Rodrigues