import module unbelieveable behaviour

Carl Banks pavlovevidence at gmail.com
Thu Jul 16 02:18:52 CEST 2009


On Jul 15, 6:12 am, Peter Fodrek <peter.fod... at stuba.sk> wrote:
> Dear conference!
>
> I have test Why python based script for HeeksCNC post-processing does not
> work...  And I've got unbelievable behavior  When importing module module
> manually it works, but same opertaion from script does not
>  work as seen
>
> /opt/HeeksCAD8/HeeksCNC> python
> Python 2.6 (r26:66714, Feb  3 2009, 20:49:49)
> [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> import nc.rez
>
> /opt/HeeksCAD8/HeeksCNC> python test.py
> Traceback (most recent call last):
>   File "test.py", line 7, in <module>
>     import nc.rez
> ImportError: No module named rez
>
> /opt/HeeksCAD8/HeeksCNC> python ./test.py
> Traceback (most recent call last):
>   File "./test.py", line 7, in <module>
>     import nc.rez
> ImportError: No module named rez
>
> Would anyone be helpful for me to get more information about this problem
> because  pydb does not show anything usable for me,please?


That's a tricky one, indeed.

Here's my guess: test.py is a symlink to a file in another directory.

A major difference between interactive and script mode is the value of
sys.path[0], which is the directory Python uses for local modules and
packages.  Python uses the current directory when running in
interactive mode, but it uses the directory where the script is
located when it is called on a script.

Normally, when you run python on a script in the current directory,
the behavior is the same as interactive mode, because the directory
where the script is located is the current directory.  But there's the
gotcha: when you run python on symlinked file, Python sets sys.path[0]
to the directory containing the actual file, not the directory
containing the symlink.  Thus even if the symlink is in the current
directory, sys.path[0] is set to a different one.

As a workaround, test.py should explicitly add '' to sys.path:

sys.path.insert(0,'')


There is another notable difference in behavior between the two
modes.  In interactive mode, sys.path[0] is ''.  If you were to change
the current directory from within Python, using os.chdir(), then
future imports will occur relative to the new current directory.
However, if you run Python from a script, sys.path[0] is an actual
directory name, so that even if you chdir, any future imports will
still occur relative to the original directory.

Pretty confusing if you ask me.  Unfortunately Python is very
unPythonic when it comes to importing.  :(


Carl Banks



More information about the Python-list mailing list