Category Archives: Python

[Solved] python Install pip Error: zipimport.ZipImportError: can’t decompress data; zlib not available

Phenomenon:

Solution:

1. Install dependent packages

yum -y install zlib*

2. Recompile Python

#The catalog is based on the production environment itself
[root@wangzy software]# cd Python/
[root@wangzy Python]# ./configure --prefix=/usr/local/python3

#Compile and install
[root@wangzy Python]# make && make install

# re-install
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py

[Solved] Tensorflow Error: ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray)

Problem description

When an array is sent to tensorflow training, the following errors are reported:

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray)

The array element is an array, and the shape of each array element is inconsistent. An example is as follows:

cropImg[0].shape = (13, 13, 3)
cropImg[1].shape = (14, 13, 3)
cropImg[2].shape = (12, 13, 3)

environment

python 3.7. 9

tensorflow 2.6. 0

keras 2.6. 0

Solution:

There are many similar error reports on stackoverflow, which roughly means that the data type is wrong. The converted data type is not the data type in brackets, such as:

Unsupported object type numpy.Ndarray means that the cropimg array element is not numpy Ndarray type

Bloggers were puzzled and tried many methods. They all showed that the data type of the cropimg array element was numpy Ndarray, but the error always exists

Later, I suddenly realized that when generating the cropimg array, there was a warning:

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  cropImg_ar = np.array(img_list)

The cropimg array element is an array with inconsistent shapes, which indicates that the cropimg array element type is actually object. Is it caused by tensorflow not accepting object type data

After converting the cropimg array elements to shape consistency, the problem is solved

 

[Solved] Django error: AttributeError: ‘QuerySet’ object has no attribute ‘id’

summary:

Login users can view the article details, and visitors can’t view the article details and report errors

Error codes are as follows:

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
--The above codes are basically to determine the identity of the visitor--
1
The value of next_topic is: <QuerySet [<Topic: Topic object (2)>, <Topic: Topic object (3)>]>
Internal Server Error: /v1/topics/qq66907360
Traceback (most recent call last):
  File "D:\Program Files (x86)\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Program Files (x86)\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Program Files (x86)\Python\Python310\lib\site-packages\django\views\generic\base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\Program Files (x86)\Python\Python310\lib\site-packages\django\views\generic\base.py", line 101, in dispatch
    return handler(request, *args, **kwargs)
  File "D:\PycharmProjects\linuxTangblog\topic\views.py", line 151, in get
    res = self.make_topic_res(author,author_topic,is_self)
  File "D:\PycharmProjects\linuxTangblog\topic\views.py", line 29, in make_topic_res
    next_id = next_topic.id if next_topic else None
AttributeError: 'QuerySet' object has no attribute 'id'
[17/Dec/2021 15:02:20] "GET /v1/topics/qq66907360?t_id=1 HTTP/1.1" 500 79151

Troubleshooting process:

After traversing the ‘queryset’ object, I found that the traversed data is an object object object, and then I took the value with the object value,

The value of next_topic is: <QuerySet [<Topic: Topic object (2)>, <Topic: Topic object (3)>]>
next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author,limit='public')
for i in next_topic:
    print(i.id)

Then I thought that the previous article and the next article only need one value, but obviously the queryset object has multiple values, which does not meet the expectation. Then I look at the code and find that the condition of first () or last () is not written

        if is_self:
            #Next
            next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author).first()
            #previous
            last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author).last()
        else:
            next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author,limit='public')
            last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author,limit='public')

Solution:

Add the condition of first() or last()

        if is_self:
            #Next
            next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author).first()
            #previous
            last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author).last()
        else:
            next_topic = Topic.objects.filter(id__gt=author_topic.id,author=author,limit='public').first()
            last_topic = Topic.objects.filter(id__lt=author_topic.id,author=author,limit='public').last()

[Solved] python3.7+django2.2 Error: AttributeError: ‘str’ object has no attribute ‘decode’

Environment: python3.7+django2.2
Error message:
AttributeError: ‘str’ object has no attribute ‘decode’

Solution:
Find the django file under the python file>db file>backends>mysql>operations.py
open a file:
Ctrl+f search query.decode after opening

 

Then change query.decode to query.encode
#Original code:

query = getattr(cursor, '_executed', None)
if query is not None:
query = query.decode(errors='replace')
return query

#change into:

query = getattr(cursor, '_executed', None)
if query is not None:
query = query.encode(errors='replace')
return query

Done!

[Solved] Python: third-party library fire Install Error

1. Linux Environment

report errors

DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality.
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/
Collecting fire
  Downloading https://mirrors.aliyun.com/pypi/packages/11/07/a119a1aa04d37bc819940d95ed7e135a7dcca1c098123a3764a6dcace9e7/fire-0.4.0.tar.gz (87 kB)
     |????????????????????????????????| 87 kB 3.8 MB/s 
    ERROR: Command errored out with exit status 1:
     command: /usr/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-6x44h_/fire/setup.py'"'"'; __file__='"'"'/tmp/pip-install-6x44h_/fire/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-szF2KD
         cwd: /tmp/pip-install-6x44h_/fire/
    Complete output (1 lines):
    error in fire setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Solution:

This problem is mainly because the version of setuptools is too low, so you only need to upgrade the software. Install fire after upgrading the version of setuptools

]# pip install setuptools -U
]# pip install fire

2. Windows Environment

report errors

(env) Lenovo@Lenovo python> pip install fire
Traceback (most recent call last):
  File "D:\Python27\Lib\runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "D:\Python27\Lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "F:\workspace\cli\python\env\Scripts\pip.exe\__main__.py", line 4, in <module>
  File "f:\workspace\cli\python\env\lib\site-packages\pip\_internal\cli\main.py", line 10, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "f:\workspace\cli\python\env\lib\site-packages\pip\_internal\cli\autocompletion.py", line 9, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "f:\workspace\cli\python\env\lib\site-packages\pip\_internal\cli\main_parser.py", line 7, in <module>
    from pip._internal.cli import cmdoptions
  File "f:\workspace\cli\python\env\lib\site-packages\pip\_internal\cli\cmdoptions.py", line 25, in <module>
    from pip._internal.cli.progress_bars import BAR_TYPES
    _BaseBar = _select_progress_class(IncrementalBar, Bar)  # type: Any
  File "f:\workspace\cli\python\env\lib\site-packages\pip\_internal\cli\progress_bars.py", line 48, in _select_progress_class
    six.text_type().join(characters).encode(encoding)
LookupError: unknown encoding: cp65001

Solution

This problem is mainly caused by the character encoding on the command line. Some characters cannot be used normally. Just modify the default character encoding. If you continue to report errors, you can modify it to other character codes

(env) Lenovo@Lenovo python> chcp 1252 //Modify to 1252 (ANSI)
(env) Lenovo@Lenovo python> pip install fire

 

[Solved] Pychart Install a Third-part Library error: no such option: — bulid dir

Error content: no such option: — bulid dir

pycharm relies on -- build dir to install third-party libraries. This flag has been removed since the version of 20.2.

Solution:

1. Switch the version of PIP: Python - M PIP install PIP == 20.2.4 #### switch the version of PIP

2. Update pychart: click Help -> check for updates in pychart

[Solved] yum Execute Error: -bash: /usr/bin/yum: /usr/bin/python3.7: bad interpreter: No such file or directory

Today, we upgraded our company’s products. As a result, yum was used during the installation. As a result, the yum command reported an error: “ - bash:/usr/bin/Yum:/usr/bin/Python 3.7: bad interpreter: no such file or directory"

Check the python Version (which Python). Python 3.0 is installed on the system 6. See the meaning of the error prompt. Yum needs to use pthon3 7 as an interpreter.

So you need to upgrade python, but Yum is not available. What should I do?One way is to manually download the RPM package of Python 3.7. Another way is:

(1) Modify the yum file (VIM/usr/bin/yum, insert, and then WQ save), and change the python version that Yum depends on to the version on the computer, as follows (/usr/bin/Python 3.7 is replaced by/usr/bin/Python):

(2) Create a python soft connection (use your own version of Python):

 ln -s /usr/bin/python /usr/bin/python3

(3) Update using yum. The results are as follows:

(4) finally, upgrade Python to 3.7

[Solved] django.db.utils.ProgrammingError: (1146, u”Table” xxx doesn’t exist”)

1. Delete a table in the database and re-execute Python manage Error in py migrate, prompting that this table does not exist.

2. This is mainly because Django usually creates a new table during the first migration, and the subsequent tables will not create a new table, but only check the changes of fields. Therefore, since we have deleted this table, Django will naturally report an error when checking the changes of fields in this table.

3. The solution is still to execute Python manage Py makemigrations and python manage Py migrate only deletes the record of the table created during the first migration before executing this. Otherwise, it detects that it has been executed for the first time, and the table will not be created later.

(1) In the app module, there is a migrations folder. Except for the first two files, other files are deleted. In fact, every time there is a change, a file will be generated here. The following 001_initial.py is generated during the first migration according to its name. That is, because it exists, no table will be created every time it is executed in the future.

(2) Secondly, there are corresponding records in the database, which should also be deleted. Let’s take a closer look at what is stored in the database. In django_migrations, this table stores records of each migration. Of course, what module is recorded and the corresponding file name. For example, our module here is dtheme, and the file here is 001_initial, which is similar to ours There are one-to-one correspondence in the folder. Similarly, delete this record.

4. Then execute Python manage Py makemigrations and python manage Py migrate is OK. It should be noted that if there are other models under the app module, the tables created by other models should also be deleted, which is equivalent to that our solution is for the whole app module, and all tables will be regenerated if they need to be executed, otherwise some existing errors will be prompted.

[Solved] Python OSError: Could not find lib geos_c.dll or load any of its variants

Python always reports oserror: could not find lib GEOS when running after packaging exe_c. Missing GEOS DLL or load any of its variants_c.DLL error,

And it’s very strange that when you run Python files directly, there is no error, and the typed exe will report an error. It’s considered that the dependency is not typed in,

 

Solution:

1. First, make sure there are GEOS DLL and geos_c. DLL. If not, execute PIP install GEOS to install it

2. Find GEOS DLL and geos_c.DLL location

3. Yes Data = [] in spec file add GEOS DLL and geos_c.DLL dependency

datas=[(“D:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\Lib\\site-packages\\shapely\\DLLs\\geos.dll”,”.”), (“D:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\Lib\\site-packages\\shapely\\DLLs\\geos_c.dll”,”.”)],

4. Pass Spec compile exe, pyinstaller XXX Spec will do