Python script error AttributeError: 'Module' Object Has No Attribute'XXX 'Solution

created at 06-26-2021 views: 38

Recently, I have encountered a problem during the writing of the Python scripting. It is quite quiteer: Python scripts are completely no problem, but execute the total error AttributeError: 'Module' Object Has no attribute ‘xxx’. This is actually a problem with .pyc file.

identify the problem:

check the source file of the Import library, discover the existence of the source file and there is no error, and there is a source file .pyc file

Problem solution:

1. When you name the PY script, don't use the Python reserved words, module names, etc.

2. Delete the .pyc file of the library (because the PY script will generate .pyc files each time; in the case of generating .pyc files, if the code is not updated, the run is still PYC, so you have to delete. PYC file), re-run the code; or find a environment that can run the code, copy the.pyc file of the current machine.

Example:

As follows the Python code, execute the error "AttributeError: 'Module' Object Has No Attribute 'Urlopen'", after updating the Python27\Lib\urllib2.pyc file, you can run it.


import urllib2

 url = "http://www.google.com"
 f = urllib2.urlopen(url, timeout=5).read()
 print len(f)       

PYC file introduction

The PYC file is the Bytecode file after Python compiling. As long as you run the PY file, the Python compiler will automatically generate a corresponding PYC block code file. This PYC paragraph code file, through the Python interpreter, generate machine code run (this is why PYC files can be deployed across platforms, similar to Java's cross-platform, Java, JVM running bytecode files). The next call calls PYC directly without calling the PY file. It has changed until you have changed this PY file. The Python interpreter will check the generation time in the PYC file, compare the modification time of the PY file, if PY is updated, then generate a new PYC.

created at:06-26-2021
edited at: 06-26-2021: