wugology
wugology

Reputation: 193

from X import Y works in the terminal, but not in a script executed from the terminal

I'm running Python 2.7.3 and Mac OS 10.8.5. I downloaded all the packages and data from nltk.org and have been able to use them quite successfully in the terminal one line at a time. I want to write my own script with them, and this seems to be a problem.

If I open the terminal and type:

  cd nltk_data
  python
  from nltk.book import *

it executes perfectly. If I open the terminal and type:

python mycode1.py

where "mycode1.py" looks like this:

  import os
  os.chdir('MyDirectory/nltk_data')
  from nltk.book import *

it fails with the error:

ImportError: No module named book

I thought maybe it was the working directory causing problems, even though adding os.getcwd() to the above code shows I'm in the right working directory. If I open up a fresh terminal and try:

    cd nltk_data
    python mycode2.py 

Where mycode2.py looks like:

from nltk.book import *

It fails with the same error. I can run scripts from the terminal though.

python four.py

where four.py looks like:

print 2+2

Works fine. The * doesn't seem to be the problem either, as I tried the above with a specific item as well, with the same results. It seems that the from X import Y function within a script run from the terminal is the problem, but from X import Y in the terminal works. I tried several variants, like:

    import nltk
    import nltk.book

And still get that "book" is a module that doesn't exist if I ask for it from a script (but again it works fine if I ask for it from the terminal).

I tried searching for a similar error and there was something about appending sys.path but I understand how/why I would do this? I also am somewhat confused since "book" is not the name of any file or folder in the nltk_data directory I downloaded. I'm really not sure where to go from here.

Upvotes: 2

Views: 697

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

You've called something else "nltk.py". Remove/rename that file and any associated compiled bytecode files.

Upvotes: 3

Related Questions