Category Archives: Python

[Solved] Error: unrecognized arguments: — no site packages

Error: unrecognized arguments: — no site packages

virtualenv --no-site-packages ${G_VENV_DIR}
usage: virtualenv [--version] [--with-traceback] [-v | -q] [--app-data APP_DATA] [--clear-app-data] [--discovery {builtin}] [-p py] [--creator {builtin,cpython3-win,venv}] [--seeder {app-data,pip}] [--no-seed] [--activators comma_sep_list]
                  [--clear] [--system-site-packages] [--copies] [--download | --no-download] [--extra-search-dir d [d ...]] [--pip version] [--setuptools version] [--wheel version] [--no-pip] [--no-setuptools] [--no-wheel]
                  [--symlink-app-data] [--prompt prompt] [-h]
                  dest
virtualenv: error: unrecognized arguments: --no-site-package

If the version is greater than 20 and the virtualenv version is greater than 20, it is the default no site packages parameter

View virtualenv version

virtualenv --version

1. Downgrading

pip install --upgrade virtualenv==16.7.9

2. remove –no-site-package

virtualenv ${G_VENV_DIR}

Keras import a custom metric model error: unknown metric function: Please ensure this object is passed to`custom_object‘

Keras’s model defines metric or loss,
there is no problem when saving to H5, but when using load_ When importing the model, an error will be reported:

unknown metric function: HammingScore. Please ensure this object is passed to the custom_ objects argument.

This is because the custom parameters are not passed in. There are two solutions:

          1. if you only need to predict and no longer train, you can add

        compile = false directly

model = keras.models.load_model('model.h5', compile = False)

If you need further training or modification, add your own metrics code and compile it again

model.compile(loss='binary_crossentropy',
              optimizer=Ada,
              metrics=[HammingScore]) # 这里HammingScore是我自定义的metric
      1. when importing, the user-defined metric/loss is passed into

Custom as a key value_ objects

      1. :
model = keras.models.load_model('model.h5', custom_objects={'HammingScore': HammingScore} )

Note that the key value should be consistent

How to Solve PyInstaller Package Error: ModuleNotFoundError: No module named ‘xxxx‘

In the venv environment, there is no exception in the packaging process when the command line pyinstaler is used to execute the packaging command. However, after the packaging is successful, it is executed. In the venv environment, the packaging process is normal when the command line pyinstaler is used to execute the packaging command. After the packaging is successful, the following similar errors appear when the dist/xxx.exe file is executed:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    import jcw
  File "PyInstaller\loader\pyimod03_importers.py", line 531, in exec_module
  File "jcw.py", line 3, in <module>
    import pandas as pd
ModuleNotFoundError: No module named 'pandas'

Solution:

Because the running environment is venv virtual environment, the command line packaging may use the installation environment of Python in the computer, that is, the global environment and dependency library, which leads to the failure to include the required modules in the packaging.

Use another packaging method of pyinstaler official website, Python code to run the packaging command, such as:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import PyInstaller.__main__
import os


if __name__ == '__main__':
    pyi_args = [
        '--upx-dir=F:\\soft\\upx-3.96-win64',
        '--clean',
        '--add-data={0};.'.format(os.path.realpath('cfg.ini')),
        '--add-binary={0};driver'.format(os.path.realpath('driver/chromedriver.exe')),
        '--name=demo',
        'main.py',
        '-y'
    ]
    print("pyinstaller " + " ".join(pyi_args))
    PyInstaller.__main__.run(pyi_args=pyi_args)

Several ways of online search don’t work (you can try your own environment or not)

1.Move the import statement from the file header to the code block

2.Command line use — hidden import = missing module

 

 

Djangorestframework-simplejwt: ‘str‘ object has no attribute ‘decode‘ [Solved]

Problem description

Python v3.6.6Django v3.2.4djangorestframework v3.12.4djangorestframework-simplejwt v4.4.0

When testing the interface after running runserver command, the error of background printing is as follows

Traceback (most recent call last):
  File "D:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Program Files\Python36\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\Python36\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\views.py", line 27, in post
    serializer.is_valid(raise_exception=True)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid
    self._validated_data = self.run_validation(self.initial_data)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework\serializers.py", line 422, in run_validation
    value = self.validate(value)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\serializers.py", line 75, in validate
    data['refresh'] = str(refresh)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\tokens.py", line 82, in __str__
    return token_backend.encode(self.payload)
  File "D:\Program Files\Python36\lib\site-packages\rest_framework_simplejwt\backends.py", line 43, in encode
    return token.decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'

terms of settlement

Method 1

Upgrade the djangorestframework simplejwt version to 4.6.0 +

Method 2

Open
D:// program files/Python 36/lib/site packages/rest_ framework_ simplejwt\backends.py

File, edit line 43. take

return token.decode('utf-8')

It can be amended as follows

return token

explain

FileNotFoundError: Could not find module ‘D:\Anaconda3\envs\labe\Library\bin\geos_c.dll‘ [Solved]

Solution:
FileNotFoundError: Could not find module
‘D:\Anaconda3\envs\LabelImg\label\bin\geos_c.dll’ (or one of its dependencies).
Try using the full path with constructor syntax.(or one of its dependencies). Try using the full path with constructor syntax.

1, most people are not importing the “shapely” dependency. You only need to import it

pip install shapely

2. Import this or report an error, basically it is wrong with your Python version.

To download the corresponding. WHL file, the link is as follows: https://www.lfd.uci.edu/~gohlke/pythonlibs/#shapely , after entering the website, Ctrl + F can find shapely, and select the version up or down according to your own version( The author is python3.8)

#First uninstall the downloaded shapely
pip uninstall shapely
#then download the local cp38 version of shapely
pip install D:\PyCharm\Pro\OCR\PaddleOCR\PPOCRLabel\BACK\Shapely-1.7.1-cp38-cp38-win_amd64.whl

Ctypes DLL Error: FileNotFoundError: Could not find module ‘***_dll.dll‘ (or one of its dependencies).

Generally speaking, a 32-bit DLL can run on a 64 bit computer, so it has nothing to do with the number of bits in the computer. First of all, make sure that the path of the DLL file is correct. If it is correct, you will still report this error, that is, the environment is missing. Baidu search Microsoft Visual C++   2019。

Installation of X86 x64 depends on the two environments

For the record, a lot of mistakes on the Internet delayed the whole day.

pytest pluggy.manager.PluginValidationError: unknown hook’pytest_namespace’ error handling method

1. Background description

The colleague who tested last week said that the pytest+allure environment is no problem running on other people’s computers, but when running in her environment, an error was reported and asked for help. In fact, pytest has only heard of allure and never heard of it directly, but it can’t directly say that it won’t, 

Look at the environment pytest can be installed directly in the form of a python library: pip install pytest pytest-allure-adaptor pytest-rerunfailures pytest-html

Allure installation is also simple to download and decompress and then add the bin directory to the environment variable. Download link: https://github.com/allure-framework/allure2/releases/tag/2.10.0

 

2. Problem solving

2.1 Error description

The main operating errors are as follows:

pluggy.manager.PluginValidationError: unknown hook'pytest_namespace' in plugin <module'allure.pytest_plugin' from'd:\\language\\miniconda3\\e
nvs\\pytest\\lib\\site-packages\\allure\\pytest_plugin.py'>

The complete error is as follows:

F:\PycharmProjects\pytest>pytest
================================================== ================== test session starts =================================================================================================================================================================================================================================================================================== =======================================
platform win32 - Python 3.6.6, pytest-4.3.0, py-1.7.0, pluggy-0.8.1
rootdir: F:\PycharmProjects\pytest, inifile: pytest.ini
plugins: rerunfailures-6.0, metadata-1.8.0, html-1.20.0, allure-adaptor-1.7.10
collecting 1 item I
NTERNALERROR> Traceback (most recent call last):
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\_pytest\main.py", line 210, in wrap_session
INTERNALERROR> session.exitstatus = doit(config, session) or 0
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\_pytest\main.py", line 249, in _main
INTERNALERROR> config.hook.pytest_collection(session=session)
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\pluggy\hooks.py", line 284, in __call__
INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\pluggy\manager.py", line 68, in _hookexec
INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\pluggy\manager.py", line 62, in <lambda>
INTERNALERROR> firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\pluggy\callers.py", line 208, in _multicall
INTERNALERROR> return outcome.get_result()
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\pluggy\callers.py", line 80, in get_result
INTERNALERROR> raise ex[1].with_traceback(ex[2])
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\pluggy\callers.py", line 187, in _multicall
INTERNALERROR> res = hook_impl.function(*args)
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\_pytest\main.py", line 259, in pytest_collection
INTERNALERROR> return session.perform_collect()
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\_pytest\main.py", line 487, in perform_collect
INTERNALERROR> self.config.pluginmanager.check_pending()
INTERNALERROR> File "d:\language\miniconda3\envs\pytest\lib\site-packages\pluggy\manager.py", line 251, in check_pending
INTERNALERROR>% (name, hookimpl.plugin),
INTERNALERROR> pluggy.manager.PluginValidationError: unknown hook'pytest_namespace' in plugin <module'allure.pytest_plugin' from'd:\\language\\miniconda3\\e
nvs\\pytest\\lib\\site-packages\\allure\\pytest_plugin.py'>

 

2.2 Error handling

Repeatedly re-created and configured the environment, and suddenly it ran successfully. I went back to rule out the Chinese path for the project, the Chinese path for the python environment, and the conda release. After I remembered that a page on Google said it was a version problem and I followed its recommendations. Old version installed:

Finally, it is confirmed that the new version of pytest (I am currently 4.3.0) reports an error, and it will not report an error if it is replaced with version 4.0.2:

# Uninstall the installed pytest
pip uninstall pytest
4. Installation # 0 .2 version pytest
pip install pytest== 4.0. 2

Successfully run as shown below:

 

[Solved] Django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17).

CentOS comes with 3.7.17 Django, which is not supported. It must be above 3.9.0. If you want to use SQLite3 as a database, there is no way to upgrade it. If it is me, I will not use SQLite3, but use mysql

The upgrade is simple:

1. Download the latest package of SQLite3

https://www.sqlite.org/download.html

wget https://www.sqlite.org/2021/sqlite-autoconf-3350500.tar.gz

2. Compile and install

tar xf https://www.sqlite.org/2021/sqlite-autoconf-3350500.tar.gz
cd sqlite-autoconf-3350500
./configure --prefix=/usr/local/ && make && make install 

3. Change the original SQLite3 command

First check which directory SQLite3 has executable files in

(python36) [[email protected] servermonitor]# whereis sqlite3
 sqlite3: /usr/bin/sqlite3 /usr/local/bin/sqlite3 /usr/include/sqlite3.h /usr/share/man/man1/sqlite3.1.gz (python36) [[email protected] servermonitor]#

It is found that/usr/bin/SQLite3 is old, 3.7.17. If you are not sure, just execute it

/usr/bin/sqlite3 –verssion

Then replace the old version

mv /usr/bin/sqlite3 /usr/bin/sqlite3_3.7.17
 ln -s /usr/local/bin/sqlite3 /usr/bin/sqlite3

4. Change the library path

Many small partners went to the above and tested it. They found that the same error was still reported when executing Python manage.py runserver 8080. The reason is that Django read the old library, and you can verify it yourself

(python36) [[email protected] servermonitor]# python 
Python 3.6.8 (default, Nov 16 2020, 16:55:22) [GCC 4.8.5 20150623 
(Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information.
 >>> import sqlite3
 > >>> sqlite3.sqlite_version 
 > '3.7.17'      
>>> .exit

Modifying library variables

export LD_LIBRARY_PATH="/usr/local/lib/"

Retest

(python36) [[email protected] servermonitor]# python Python 3.6.8
 (default, Nov 16 2020, 16:55:22) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information.
  >>> import sqlite3
  > >>> sqlite3.sqlite_version
  '3.35.5'          
  >>> exit()

Execution returned to normal

(python36) [[email protected] servermonitor]# python manage.py runserver 8080
 Django version 3.2.4, using settings 'servermonitor.settings' Starting development server at
http://127.0.0.1:8080/ Quit the server with CONTROL-C.

[Solved] Np.argwhere error: maximum recursion depth exceeded while calling

The complete error is: recursionerror: maximum recursion depth exceeded while calling a python object

resolvent

It is suggested to modify this usage according to the code logic, NP. Argwhere the original meaning of usage is to filter out the values that meet the conditions in numpy , such as:

np.argwhere(y == label)

It is to filter the value of y = = label , but this usage is very dangerous and can be rewritten as:

np.argwhere(sum(y == label))

Recommend another way to write code logic!!!

Python: How to Solve error While importing windpy

First of all, I met this error report

>>> import WindPy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: source code string cannot contain null bytes

It’s probably the coding problem. The solution is to use vscode to open windpy.py (just search in the computer). There is a coding button in the lower right corner. Now the UTF-8 is displayed. Originally, it seems to be utf-16le. The Chinese displayed in the text is still garbled. Click this button and select save in this format.

And then there’s the following error report

SyntaxError: 'gbk' codec can't decode byte 0xbd in position 2985: illegal multibyte sequence

The solution is to delete all the comments.

It’s the last mistake.

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\**myfiles**\\Python\\Python38\\site-packages\\WindPy.pth'

The solution is to look for open in windpy.Py and comment all the following lines

Change the line that reads the library to the address of windpy.dll

    # pathfile=open(sitepath)
    # dllpath=pathfile.readlines();
    # pathfile.close();

    # sitepath=dllpath[0]+"\\WindPy.dll" 

    c_windlib=cdll.LoadLibrary('D:\\**install_WIND_files**\\x64\\WindPy.dll')

Just fine. I hope I can help you not to fall into the pit

[How to Solve] Python TypeError: ‘int‘ object is not subscriptable

The title is the teacher’s lesson, which is adapted from the python language design basis of Songtian teacher of Beijing Institute of technology, page 4.7, 121

Please modify example 5: body mass index BMI with exception handling, so that it can receive and process any input from the user

while True:
try:
Height, weight = Eval (input (“please input height (m) and weight (kg) [separated by commas]:”)
0         bmi = weight/pow(height,2)
Print (“BMI value is: {. 2F}”. Format (BMI))
0         if height > 3:
if h[:-1].isinstance():
Print (“height value is {. 2F}”. Format (height))
0                 break
elif weight > 150:
if   w[:-1].isinstance():
Print (“body weight value is {. 2F}”. Format (weight))
0                 break
except NameError:
Print (“input error, please input correct information”)
the     else:
Print (“no exception occurred”)
finally:
Print (“complete”)

The cause of the error is an operation on an object that cannot be operated on

The original errors were height [: – 1]. Isinstance and weight [: – 1]. Isinstance, which were changed to h and W

Please input height (m) and weight (kg) [comma separated]: 4,85
BMI value: 5.31
input error, please input correct information
complete
please input height (m) and weight (kg) [comma separated]: 1.85,85
BMI value: 24.84
no abnormality
complete
please input height (m) and weight (kg) [comma separated]: 1.85, 200
BMI value: 58.44
input error, please input correct information
complete
please input height (m) and weight (kg) [separated by commas]: