7

When running a Python 3 script of mine, I encounter a "Bad magic number" error (while the script tries to import another module). At first I imagined it's because there are .pyc files built by Python 2. I deleted the __pycache__ directory and reran the script, but the interpreter still gives me the same error when importing that module. Any ideas?

UPDATE: To clarify, I should mention that the import statement in the script doesn't cause the error by itself. Here's the stack trace:

Traceback (most recent call last):
  File "../mvc/test.py", line 6, in <module>
    from property import Property
  File "/home/mostafa/python/mvc/property.py", line 1, in <module>
    from owned import owned
  File "/home/mostafa/python/owned/__init__.py", line 1, in <module>
    from list import OwnedList
ImportError: Bad magic number in /home/mostafa/python/list.pyc
Elektito
  • 3,863
  • 8
  • 42
  • 72
  • A similar question as yours: http://stackoverflow.com/questions/514371/whats-the-bad-magic-number-error. Did you check to ensure your import of module does not depend on any other modules or __builtins__? – Vijay May 17 '11 at 17:29
  • I did check out that question. My script has only two imports: one is sys (which works fine since it's placed before the other import), and one is the other module which causes the error. – Elektito May 17 '11 at 17:33
  • Perhaps try running `python -v script.py`. The `-v` flag will cause python to print out all the imports as modules are loaded. This may supply a clue about where the problem is occurring. – unutbu May 17 '11 at 17:37
  • 2
    Have you tried deleting /home/mostafa/python/list.pyc? Assuming you have `list.py`, python3 will generate a new list.pyc. – unutbu May 17 '11 at 17:42
  • [This](http://pastebin.com/sd0MZ5Rq) is what I get when I run "python3 -v test.py". I can't say I see anything that can help, but maybe I'm missing something. – Elektito May 17 '11 at 17:43
  • @unutbu That's it. I'm afraid I didn't read the stack trace carefully. I expected the .pyc file to be in the "owned" directory, forgetting that an old version of list.pyc existed in the Python path. Thank you. Perhaps, you want to post this as an answer so I can accept it. – Elektito May 17 '11 at 17:49

1 Answers1

12

The last line of the stack trace shows the path to the pyc file causing the error:

ImportError: Bad magic number in /home/mostafa/python/list.pyc

Assuming you have list.py in your PYTHONPATH, you can delete /home/mostafa/python/list.pyc. When you import list, Python3 will generate a new version of list.pyc based on list.py.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677