Category Archives: Python

[Solved] Python-pip Upgrade ERROR: AttributeError: ‘NoneType’ object has no attribute ‘bytes’

Normal PIP upgrade command:

python -m pip install --upgrade pip

Create a python project in pytharm, and pytharm will automatically build a new Python environment to use in the current directory

python -m pip install --upgrade pip

I’ll report an error

AttributeError: 'NoneType' object has no attribute 'bytes'

You can use the following methods

easy_install -U pip

[Solved] AttributeError: ‘module’ object has no attribute ‘gfile’

While running TensorFlow’s classify_ image, getting AttributeError: ‘module’ object has no attribute ‘gfile’

When you run tensorflow’s classify_ Image, the error prompt “attributeerror: ‘module’ object has no attribute ‘gfile'”

Problem Description:

I got an error. When I run tensorflow sample file, under Imagenet model

I am getting this error while running the sample file given with TensorFlow, in the imagenet model,

File "classify_image.py", line 154, in run_inference_on_image
if not tf.gfile.Exists(image):

AttributeError: ‘module’ object has no attribute ‘gfile’

I have tried installing using both, from pip as well as source, on virtualserver as well, still I get this error.

I’ve tried installing both methods, from pip to source, at virtualserver, etc., but still get this error.

This gfile stuff was added 6 days ago in this commit — github.com/tensorflow/tensorflow/commit/… , might be worth filing an issue on github. As a workaround, you can undo the gfile stuff locally back into os.path, it’s only a few lines –Yaroslav Bulatov

AttributeError: module ‘requests’ has no attribute ‘get’ [How to Solve]

I find that the file directly uses requests. Get (URL) to prompt me for attributeerror: module ‘requests’ has no attribute’ get ‘

The solution is as follows:

The python source file has the same name as the keyword

1. When naming py script, do not use the same reserved word and module name as python

2. Delete the. PyC file of the library (because the. PyC file is generated every time the PY script runs; When the. PyC file has been generated, if the code is not updated, the runtime will still run PyC, so delete the. PyC file and rerun the code; Or find an environment that can run the code, copy and replace the. PyC file of the current machine

Later, I found that there is a program with a requests.py file in my path. If I delete it, I won’t report this kind of error

How to Solve Name Error: module ‘yagmail’ has no attribute ‘SMTP’

when naming a file name, we should avoid coinciding with the system package name

Reprinted from: https://stackoverflow.com/questions/16512256/no-attribute-smtp-error-when-trying-to-send-email-in-python

I am trying to send an email in Python:

import smtplib


fromaddr = '......................'  
toaddrs  = '......................'  
msg = 'Spam email Test'  

username = '.......'  
password = '.......'

server = smtplib.SMTP('smtp.gmail.com', 587)  
server.ehlo()
server.starttls()
server.login(username, password)  
server.sendmail(fromaddr, toaddrs, msg)  
server.quit()

I understand that this is probably not the correct message format.

Anyways, I get an error:

C:\.....>python email.py
Traceback (most recent call last):
  File "email.py", line 1, in <module>
    import smtplib
  File "C:\.....\Python\lib\smtplib.py", line 47,
 in <module>
    import email.utils
  File "C:\.....\email.py", line 15, in
<module>
    server = smtplib.SMTP('smtp.gmail.com', 587)
AttributeError: 'module' object has no attribute 'SMTP'

I don’t quite understand what I am doing wrong here… Anything incorrect?

 

 

Solution:

Method1:

Python already has an email module. Your script’s name is email.py, which is preventing smtplib from importing the built-in email module.

Rename your script to something other than email.py and the problem will go away.

 

Method 2:

import smtplib
conn = smtplib.SMTP('imap.gmail.com',587)
conn.ehlo()
conn.starttls()
conn.login('[email protected]', 'your_password')

conn.sendmail('[email protected]','[email protected]','Subject: What you like? \n\n Reply Reply Reply')
conn.quit()

[Solved] pipenv shell:AttributeError: ‘module’ object has no attribute ‘run’

When using pipenv shell to switch to virtual environment, an error is reported: attributeerror: ‘module’ object has no attribute ‘run’

You can see that there is an error in line 62 of the file D:: (program) python34 (LIB) site packages (pipenv) shells. Py, which indicates that the module does not have the property of run, so you go to line 62 of the file to see it

Select run and Ctrl + B to find the source code. The source code is as follows:

if sys.version_info >= (3, 6):
        # Nearly same args as Popen.__init__ except for timeout, input, and check
        def run(args: _CMD,
                timeout: Optional[float] = ...,
                input: Optional[_TXT] = ...,
                check: bool = ...,
                bufsize: int = ...,
                executable: _PATH = ...,
                stdin: _FILE = ...,
                stdout: _FILE = ...,
                stderr: _FILE = ...,
                preexec_fn: Callable[[], Any] = ...,
                close_fds: bool = ...,
                shell: bool = ...,
                cwd: Optional[_PATH] = ...,
                env: Optional[_ENV] = ...,
                universal_newlines: bool = ...,
                startupinfo: Any = ...,
                creationflags: int = ...,
                restore_signals: bool = ...,
                start_new_session: bool = ...,
                pass_fds: Any = ...,
                *,
                encoding: Optional[str] = ...,
                errors: Optional[str] = ...) -> CompletedProcess: ...
    else:
        # Nearly same args as Popen.__init__ except for timeout, input, and check
        def run(args: _CMD,
                timeout: Optional[float] = ...,
                input: Optional[_TXT] = ...,
                check: bool = ...,
                bufsize: int = ...,
                executable: _PATH = ...,
                stdin: _FILE = ...,
                stdout: _FILE = ...,
                stderr: _FILE = ...,
                preexec_fn: Callable[[], Any] = ...,
                close_fds: bool = ...,
                shell: bool = ...,
                cwd: Optional[_PATH] = ...,
                env: Optional[_ENV] = ...,
                universal_newlines: bool = ...,
                startupinfo: Any = ...,
                creationflags: int = ...,
                restore_signals: bool = ...,
                start_new_session: bool = ...,
                pass_fds: Any = ...) -> CompletedProcess: ...

But look at the first line, if sys. Version_ info >= ( 3, 6): let’s guess for a moment. This 3.6 is the version number of Python. If the version is greater than 3.6, use the first run function, otherwise use the second run function. What’s the difference between the two functions?The first run function has two more lines

         encoding: Optional[str] = ...,
               errors: Optional[str] = ...)

However, since the version greater than 3.6 and less than 3.6 will call the existing run function, why will an error be reported?Let’s take a look at the more complete code

I don’t know if I have noticed that when the version is greater than 3.5, I will go to the second if to judge whether it is greater than 3.6. However, my current version is 3.4.4, so I don’t satisfy the if judgment greater than 3.5, but satisfy the if judgment greater than 3.3. In this case, the following methods are all call (in fact, as long as the version & lt; 3.5, call method should be called)

if sys.version_info >= (3, 5):
    class CompletedProcess:
        # morally: _CMD
        args = ...  # type: Any
        returncode = ...  # type: int
        # morally: Optional[_TXT]
        stdout = ...  # type: Any
        stderr = ...  # type: Any
        def __init__(self, args: _CMD,
                     returncode: int,
                     stdout: Optional[_TXT] = ...,
                     stderr: Optional[_TXT] = ...) -> None: ...
        def check_returncode(self) -> None: ...

    if sys.version_info >= (3, 6):
        # Nearly same args as Popen.__init__ except for timeout, input, and check
        def run(args: _CMD,
                timeout: Optional[float] = ...,
                input: Optional[_TXT] = ...,
                check: bool = ...,
                bufsize: int = ...,
                executable: _PATH = ...,
                stdin: _FILE = ...,
                stdout: _FILE = ...,
                stderr: _FILE = ...,
                preexec_fn: Callable[[], Any] = ...,
                close_fds: bool = ...,
                shell: bool = ...,
                cwd: Optional[_PATH] = ...,
                env: Optional[_ENV] = ...,
                universal_newlines: bool = ...,
                startupinfo: Any = ...,
                creationflags: int = ...,
                restore_signals: bool = ...,
                start_new_session: bool = ...,
                pass_fds: Any = ...,
                *,
                encoding: Optional[str] = ...,
                errors: Optional[str] = ...) -> CompletedProcess: ...
    else:
        # Nearly same args as Popen.__init__ except for timeout, input, and check
        def run(args: _CMD,
                timeout: Optional[float] = ...,
                input: Optional[_TXT] = ...,
                check: bool = ...,
                bufsize: int = ...,
                executable: _PATH = ...,
                stdin: _FILE = ...,
                stdout: _FILE = ...,
                stderr: _FILE = ...,
                preexec_fn: Callable[[], Any] = ...,
                close_fds: bool = ...,
                shell: bool = ...,
                cwd: Optional[_PATH] = ...,
                env: Optional[_ENV] = ...,
                universal_newlines: bool = ...,
                startupinfo: Any = ...,
                creationflags: int = ...,
                restore_signals: bool = ...,
                start_new_session: bool = ...,
                pass_fds: Any = ...) -> CompletedProcess: ...

# Same args as Popen.__init__
if sys.version_info >= (3, 3):
    # 3.3 added timeout
    def call(args: _CMD,
             bufsize: int = ...,
             executable: _PATH = ...,
             stdin: _FILE = ...,
             stdout: _FILE = ...,
             stderr: _FILE = ...,
             preexec_fn: Callable[[], Any] = ...,
             close_fds: bool = ...,
             shell: bool = ...,
             cwd: Optional[_PATH] = ...,
             env: Optional[_ENV] = ...,
             universal_newlines: bool = ...,
             startupinfo: Any = ...,
             creationflags: int = ...,
             restore_signals: bool = ...,
             start_new_session: bool = ...,
             pass_fds: Any = ...,
             timeout: float = ...) -> int: ...
else:
    def call(args: _CMD,
             bufsize: int = ...,
             executable: _PATH = ...,
             stdin: _FILE = ...,
             stdout: _FILE = ...,
             stderr: _FILE = ...,
             preexec_fn: Callable[[], Any] = ...,
             close_fds: bool = ...,
             shell: bool = ...,
             cwd: Optional[_PATH] = ...,
             env: Optional[_ENV] = ...,
             universal_newlines: bool = ...,
             startupinfo: Any = ...,
             creationflags: int = ...,
             restore_signals: bool = ...,
             start_new_session: bool = ...,
             pass_fds: Any = ...) -> int: ...

If you understand this, you will know how to solve it. Just modify the source code and change run to call (if you want to use version 3.5 or above, it is recommended to change call back to run)

Using the pipenv shell again, you can switch to the virtual environment

 

from bs4 import BeautifulSoup Error [How to Solve]

Importing BeautifulSoup, the following errors (of two kinds) occur.

First error.

Python 2.7.14 (default, Sep 17 2017, 18:50:44)
[GCC 7.2.0] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> from bs4 import BeautifulSoup
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
File “/usr/local/lib/python2.7/dist-packages/bs4/__init__.py”, line 30, in <module>
from .builder import builder_registry, ParserRejectedMarkup
File “/usr/local/lib/python2.7/dist-packages/bs4/builder/__init__.py”, line 311, in <module>
from . import _html5lib
File “/usr/local/lib/python2.7/dist-packages/bs4/builder/_html5lib.py”, line 57, in <module>
class TreeBuilderForHtml5lib(html5lib.treebuilders._base.TreeBuilder):
AttributeError: ‘module’ object has no attribute ‘_base’
>>>

Solution: As the blogger said, change the name from base.py to _base.py and from base.pyc to _base.pyc.

The paths are generally the same, just copy them.

Error 2:

Then found: the file name is wrong, can not be bs4, so changed the file name, found that still reported an error: the file name is not correct.

But found a runtime cache file did not change over, and then delete, fixed

Pycharm install python packaging tools Error: AttributeError: ‘_NamespacePath’ object has no a…

Error in pychar install Python packaging tools attributeerror: ‘_ NamespacePath’ object has no attribute ‘sort’。

The error is as follows:

solution:

delete the installation directory of pychar, and do not delete the project directory venu! Re unzip the pychar directory, open pychar, and it will automatically jump to the project directory. Then select the default settings to check whether the installed library is empty or not. Click the following tip install packaging tools. This time, no error will be reported, and all the previous libraries will come out

AttributeError: ‘_csv.reader’ object has no attribute ‘next’ [How to Solve]

from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import preprocessing
from sklearn import tree
from sklearn.externals.six import StringIO

#Open CSV file 'rb' is to open a file in binary format for read-only. The file pointer will be placed at the beginning of the file
data = open(r'F:\2. Deep neural network algorithm of the basic essence\machine learning deep neural network learning foundation I 29 lessons\code and material(1)\01DTree\AllElectronics.csv','rb')
reader = csv.reader(data)
header = reader.next()

print(header)
featureList = []
lableList = []

In Python 3, the reader does not have the next() attribute. Instead, use the

header = next(reader)
from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import preprocessing
from sklearn import tree
from sklearn.externals.six import StringIO

#Open CSV file 'rb' is to open a file in binary format for read-only. The file pointer will be placed at the beginning of the file
data = open(r'F:\2. Deep neural network algorithm of the basic essence\machine learning deep neural network learning foundation I 29 lessons\code and material (1)\01DTree\AllElectronics.csv','rt')
reader = csv.reader(data)
header = next(reader)

print(header)
featureList = []
lableList = []

[Solved] ImportError:attempted relative import with no known parent package

Preface

In this article, I will analyze the cause of importerror: attached relative import with no known parent package exception. When you are running a python script. This exception may occur when a package is referenced in a relative reference mode (similar to Import.. module )

Let’s take a look at an example of this exception

Questions

Suppose you have the following directory structure:

project
├── config.py
└── demos
    ├── __init__.py
    └── demo.py

config.py contains some variables that should be used in demo.py

project/config.py

count = 5

project/demos/demo.py

from .. import config
print("The value of config.count is {0}".format(config.count))

When we try to run demo. Py , we encounter the following errors:

E:\project> python demos/demo.py
Traceback (most recent call last):
  File "demos/demo.py", line 1, in <module>
    from .. import config
ImportError: attempted relative import with no known parent package

The Python interpreter threw an exception without a parent package. Why

Let’s see how the Python interpreter parses the relevant modules. From PEP 328, we find an introduction to the relative imports :

Relative imports use a module’s __name__ attribute to determine that module’s position in the package hierarchy. If the module’s name does not contain any package information (e.g. it is set to __main__ ) then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Relative imports determine the module's location in the package hierarchy by using the module's __name__ attribute. If the module's name does not contain any package information (for example, it is set to __main__), then the relative reference assumes that this module is the top-level module, regardless of the module's actual location on the filesystem.

In other words, the algorithm for solving the module is based on the value of the __name__sum __package__variable. Most of the time, these variables do not contain any package information—for example, when  __name__=  __main__ and  __package__ =  None , the python interpreter does not know which package the module belongs to. In this case, relative references will consider this module to be the top-level module, regardless of the actual location of the module on the file system.

To demonstrate this principle, let’s update the code:

project/config.py

print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))
count = 5

project/package/demo.py

print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))
from .. import config
print("The value of config.count is {0}".format(config.count))

Try running it again and you will get the following output:

E:\project> python demos/demo.py
__file__=demos/demo.py      | __name__=__main__    | __package__=None
Traceback (most recent call last):
  File "demos/demo.py", line 3, in <module>
    from .. import config
ImportError: attempted relative import with no known parent package

As we can see, the Python interpreter does not have any information about the package to which the module belongs ( 0)__ name__=__ main__ and __ package__ = none ), so it throws an exception that the parent package cannot be found

Solution 1

we create a new empty in it__ init__. Py file to convert the project directory into a package

we create a file main. Py in the parent directory of the project directory

toplevel
├── main.py
└── project
  ├── __init__.py
  ├── config.py
  └── demos
      ├── __init__.py
      └── demo.py

toplevel/main.py

print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))
import project.demos.demo

Execute the new example, and the output is as follows:

E:\toplevel>python main.py
__file__=main.py                             | __name__=__main__             | __package__=None
__file__=E:\toplevel\project\demos\demo.py   | __name__=project.demos.demo   | __package__=project.demos
__file__=E:\toplevel\project\config.py       | __name__=project.config       | __package__=project
The value of config.count is 5

Importing project.demos.demo in main. Py will set the package information of relative reference ( main. Py )__ name__ and __ package__ variable). Now, the Python interpreter can successfully resolve the relative references in project/demos/demo. Py

Solution 2

we create a new empty project in the Project folder__ init__. Py to convert the Project directory into a package

in the top level directory, use the - M parameter to call the Python interpreter to execute project.demos.demo [1]

toplevel
└── project
  ├── __init__.py
  ├── config.py
  └── demos
      ├── __init__.py
      └── demo.py

Again:

E:\toplevel>python -m project.demos.demo
__file__=E:\toplevel\project\demos\demo.py   | __name__=__main__        | __package__=project.demos
__file__=E:\toplevel\project\config.py       | __name__=project.config  | __package__=project
The value of config.count is 5

Running this command will automatically set the package information ( 0__ package__ variable). Now, the Python interpreter can successfully resolve the relative references in project/demos/demo. Py (even think that project/demos/demo__ name __=__ main__).

Note that when using the - M parameter, the executable file specified later has no . Py suffix

Note 2:

Another error that may be reported in actual use is the wrong path to execute the code

E:\toplevel>python -m project.demos.demo

Be sure to execute this command in the directory above the project

‘tensorflow‘ has no attribute ‘sub‘ [How to Solve]

When learning tensorflow, I did it according to the official example and found one

Traceback (most recent call last):
  File "interactive.py", line 10, in <module>
    sub = tf.sub(x,a)
AttributeError: module 'tensorflow' has no attribute 'sub'

As soon as I guess, I guess the name of the function has changed. Sure enough, it has been replaced by substract

# -*- coding: utf-8 -*-
import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

x.initializer.run()

sub = tf.subtract(x,a)
print(sub.eval())