0

I created a test file called test.py (contained a class named test) and saved it into documents(Mac OS X 10.9.3)

I then attempted to use this file by writing from test import test. However, I got an error telling me that there was no module named test. Please can you shed some light into this issue.

Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33

1 Answers1

1

The problem is that the Documents folder isn't usually in the PATH or PYTHONPATH, so the interpreter can't see scripts that are stored there (unless Documents happens to be the current working directory).

I can think of two solutions:

  1. Move the file test.py to somewhere within Python's path.

    You can find your PYTHONPATH with this script:

    import os
    try:
        user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
    except KeyError:
        user_paths = []
    

    (From Mark Ransom’s answer to How do I find out my python path using python?)

    You can find the system PATH with

    import sys
    print sys.path
    

    Both of these return a list of folders. If you put test.py in one of those folders, then it will be seen by the interpreter.

    For example, I usually install custom modules at

    /Library/Python/2.7/site-packages
    

    and then I can import them as normal.

  2. Manually append Documents to your path.

    You can use sys.path.append to add a directory to the path.

    If you only need to use test.py in a handful of scripts, then you can add this code to each script you want to use test.py in:

    import os
    import sys
    sys.path.append(os.path.join(os.environ['HOME'], 'Documents'))
    from test import test
    
Community
  • 1
  • 1
alexwlchan
  • 5,699
  • 7
  • 38
  • 49