Pat B.
Pat B.

Reputation: 421

ImportError in IDLE

I consider myself an intermediate user in python, and this one is a new one. Testing code in IDLE (Python 3.2.3) on Linux. Here is the entire script:

Python 3.2.3 (default, Apr 10 2013, 05:29:11) 
[GCC 4.6.3] on linux2
Type "copyright", "credits" or "license()" for more information.
==== No Subprocess ====
>>> from os import listdir, getcwd, chdir
>>> chdir('Documents/matrix')
>>> getcwd()
'/home/bradfordgp/Documents/matrix'
>>> listdir('.')
['__init__.py', 'vec.zip', 'hw1.pdf', 'politics_lab.pdf', 'submit_hw1.py', 'submit_politics_lab.py', 'test_vec.py', 'Week1', 'Week0', 'python_lab.py~', 'Week2', 'vec.pdf', '__pycache__', 'hw1.zip', 'politics_lab.zip', 'voting_record_dump109.txt', 'my_stories.txt~', 'hw1.py', 'politics_lab.py', 'submit_vec.py', 'vec.py']
>>> from vec import Vec
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    from vec import Vec
ImportError: No module named vec
>>> 

I've navigated to the correct directory, and I'm importing from the same directory, and vec.py exists. Why is in not locating a file in the local directory? Running this script from a terminal window command line works correctly.

Suggestions?

Upvotes: 1

Views: 1910

Answers (3)

zhangyangyu
zhangyangyu

Reputation: 8620

In interactive mode, import will try to import modules from the current directory after os.chdir. But in non-interactive mode, it will fail and still search from the previous directory. You can see more discussion from this issue. In non-interactive mode, you'd better do what others mention.

Upvotes: 0

Jakob Bowyer
Jakob Bowyer

Reputation: 34708

import sys
sys.path.append("/home/bradfordgp/Documents/matrix")
import vec

Rather than change to the directory, just add the location to the places python will search on import

See more here

Upvotes: 2

abhishekgarg
abhishekgarg

Reputation: 1473

use this..

import sys

sys.path.append("/home/bradfordgp/Documents/matrix")
import vec

Upvotes: 2

Related Questions