What's the bad magic number error?

后端 未结 15 2144
心在旅途
心在旅途 2020-11-22 16:56

What\'s the \"Bad magic number\" ImportError in python, and how do I fix it?

The only thing I can find online suggests this is caused by compiling a .py -> .pyc file

相关标签:
15条回答
  • 2020-11-22 17:44

    This is much more efficent than above.

    find {directory-of-.pyc-files} -name "*.pyc" -print0 | xargs -0 rm -rf
    

    where {directory-of-.pyc-files} is the directory that contains the compiled python files.

    0 讨论(0)
  • 2020-11-22 17:45

    I had a strange case of Bad Magic Number error using a very old (1.5.2) implementation. I generated a .pyo file and that triggered the error. Bizarrely, the problem was solved by changing the name of the module. The offending name was sms.py. If I generated an sms.pyo from that module, Bad Magic Number error was the result. When I changed the name to smst.py, the error went away. I checked back and forth to see if sms.py somehow interfered with any other module with the same name but I could not find any name collision. Even though the source of this problem remained a mistery for me, I recommend trying a module name change.

    0 讨论(0)
  • 2020-11-22 17:45

    Don't delete them!!! Until..........

    Find a version on your git, svn or copy folder that works.

    Delete them and then recover all .pyc.

    That's work for me.

    0 讨论(0)
  • 2020-11-22 17:46

    Deleting all .pyc files will fix "Bad Magic Number" error.

    find . -name "*.pyc" -delete
    
    0 讨论(0)
  • 2020-11-22 17:54

    This can also be due to missing __init__.py file from the directory. Say if you create a new directory in django for seperating the unit tests into multiple files and place them in one directory then you also have to create the __init__.py file beside all the other files in new created test directory. otherwise it can give error like Traceback (most recent call last): File "C:\Users\USERNAME\AppData\Local\Programs\Python\Python35\Lib\unittest\loader.py",line 153, in loadTestsFromName module = __import__(module_name) ImportError: bad magic number in 'APPNAME.tests': b'\x03\xf3\r\n'

    0 讨论(0)
  • 2020-11-22 17:54

    You will need to run this command in every path you have in your environment.

    >>> import sys
    >>> sys.path
    ['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/source_code/src/python', '/usr/lib/python3/dist-packages']
    
    

    Then run the command in every directory here

    find /usr/lib/python3.6/ -name "*.pyc" -delete
    find /usr/local/lib/python3.6/dist-packages -name "*.pyc" -delete
    # etc...
    
    0 讨论(0)
提交回复
热议问题