george.trojan at noaa.gov
Wed Jan 27 19:48:23 CET 2010
Arnaud Delobelle wrote:
> George Trojan <george.trojan at noaa.gov> writes:
>> Inspired by the 'Default path for files' thread I tried to use
>> sitecustomize in my code. What puzzles me is that the site.py's main()
>> is not executed. My sitecustomize.py is
>> def main():
>> print 'In Main()'
>> and the test program is
>> import site
>> print 'Hi'
>> The output is
>> $ python try.py
> That's normal as site.py is automatically imported on initialisation.
> So when you do:
> import site
> the module is not re-executed as it already has been imported.
> Try this:
> ---- file: foo.py
> print 'Foo'
> ---- end
> --- Interactive session
> >>> import foo # First time, print statement executed
> >>> import foo # Second time, print statement not executed
>> When I uncomment the site.main() line the output is
>> $ python try.py
>> In Main()
> Now you explicitely call site.main(), so it executes it!
>> If I change import site to import sitecustomize the output is as
>> above. What gives?
> It's normal, this time it's the first time you import it so its content
> is executed.
I understand that importing a module repeatedly does nothing. Also, I
made a typo in my previous posting - I meant sitecustomize.main(), not
site.main(). My understanding of the code in site.py is that when the
module is imported, main() is executed. main() calls execsitecustomize()
that attempts to import sitecustomize. That action should trigger
execution of code in sitecustomize.py, which is located in the current
directory. But that does not work. I changed execsitecustomize() to
"""Run custom site specific code, if available."""
That gave me the explanation why the above happens: when site is
imported, the current directory is not yet prepended to sys.path.
$ python2.6 -v try.py
'import site' failed; traceback:
Traceback (most recent call last):
File "/usr/local/Python-2.6.3/lib/python2.6/site.py", line 516, in
File "/usr/local/Python-2.6.3/lib/python2.6/site.py", line 507, in main
File "/usr/local/Python-2.6.3/lib/python2.6/site.py", line 472, in
This also explains the recipe http://code.activestate.com/recipes/552729/
I wanted to have library location specific to application without having
to explicitly change sys.path in all App-Top-Dir/bin/*.py. I thought
creating bin/sitecustomize.py would do the trick.
I guess the documentation should mention this fact. The comment in
recipe 552729 is:
Since Python 2.5 the automatic import of the module "sitecustomize.py"
in the directory of the main program is not supported any more (even if
the documentation says that it is).
More information about the Python-list