tags:

views:

275

answers:

5

I updated my python version on windows 2003 server from 2.4 to 2.5.

In 2.4 I could import a file "sub1.py" from a subdirectory c:\application\subdir\ like this:

import sub1

as long as the calling script main.py that lives in c:\application was started like this:

c:\application\subdir>python ..\main.py

But in 2.5 it no longer works for me:

C:\application\subdir>python ..\main.py
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    import sub1
ImportError: No module named sub1

Now I can put an empty file

__init__.py

into subdir and import like this:

import subdir.sub1 as sub1

Was there a change in python 2.5? This would mean the current working directory in python 2.4 was inherited from the calling process, and in python 2.5 it is set to where the main script lives.

[edit3] I corrected the question now. I must appologize that I had over-simplified the example at first and removed the cause that results in the error without checking my simplified example. [/edit3]

+5  A: 

to import sub.py you need to:

import sub      # not sub1
SilentGhost
this was a typo in the question but not in my original code.
A: 

add this directory to your python path

ezotrank
i thought i can import from the current working directory without it being on the path
+2  A: 

You can check where python searches for modules. A list of locations is contained in variable sys.path.

You can create a simple script (or execute it interactively) that shows this:

import sys

for x in sys.path:
  print x

By default, python will search the directory in which it is being executed and where the original script resides.

Also, try setting the PYTHONPATH environment variable to include ".\" directory.

miha
to find out i would have to install 2.4 again and then 2.5 again. i was hoping someone knows about a change from 2.4 to 2.5
You can check that on your 2.5 installation. You should be able to import it. Otherwise, you can do a simple test: create a file a.py with contents def foo(): print foo and then run python interactively from the directory this is in and type: import athen a.foo()and you should get a print out. Also, you can run python in verbose mode and you will get more information: python -v backups.py. Just to be on the safe side, delete compiled versions (*.pyc)
miha
+1  A: 

I assume sub1 is a typo? In your question you sometimes refer to sub, sometimes to sub1.

I would first of all check that the sub.py file exists in c:\application.

  • Check the permissions of the sub.py file and the application directory. Can the user read the sub.py file? Can the python interpreter create the *.pyc file?
  • Also, manually delete the sub.pyc file, just in case an old version of the pyc is causing the problem.
codeape
A: 

You need to make the following changes:

  • turn subdir into a package by adding an empty __init__.py file to the directory
  • change the import to: from subdir import sub1
codeape