Tag Archives: python

[Solved] error: when using the property decorator in Python, an error occurs: typeerror: descriptor ‘setter’ requires a ‘property’ object but

Error message

• When we use the property decorator, the following errors may be caused by the wrong writing of the decorator Name:

TypeError: descriptor 'setter' requires a 'property' object but received a 'function'

Problem analysis

• The reason for this error is that we write all decorator names as property instead of the same method name in our class:

Problem code

class AgeDemo(object):

    def __init__(self, age):
        self.age = age

    @property
    def age_test(self):
        return self.age

    @property.setter   # error
    def age_test(self, age):
        if not isinstance(age, int):
            raise TypeError('TypeError')
        self.age = age

Resolve error reporting

• Change the name of the decorator with an error in the figure to the same name set in our class to solve this error
the code is as follows:

class AgeDemo(object):

    def __init__(self, age):
        self.age = age

    @property
    def age_test(self):
        return self.age

    @age_test.setter # 修改的代码行
    def age_test(self, age):
        if not isinstance(age, int):
            raise TypeError('TypeError')
        self.age = age

How to Solve Opencv Reads Video Error: cv2.error

Recently, due to the needs of the project, I often need to use OpenCV to read video. I often encounter a problem that an error will be reported after reading the video. Although it does not affect the code results, I really can’t stand being picky.

Error reporting procedures:

# -*-coding:utf-8-*-
"""
File Name: read_video.py
Program IDE: PyCharm
Create File By Author: Hong
"""
import cv2


def read_video(video_path: str):
    """
    OpenCV read video widget, solve the video read error problem
    :param video_path: input the path of the video file to be read
    :return: no return value
    """
    print('Video path:', video_path)
    cap = cv2.VideoCapture(video_path)
    while cap.isOpened():
        # get a frame
        ret, frame = cap.read()

        cv2.imshow("capture", frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    print('Read through the video!')
    cap.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    path = r'D:\multi_insect_videos\multi_object00.mp4'
    read_video(path)

You can read the video normally, but the result will output an error

Traceback (most recent call last):
  File "E:/PyCharmDocument/create_ST_image/multi_insect_processing/crop_video_to_images.py", line 76, in <module>
    read_video(path)
  File "E:/PyCharmDocument/create_ST_image/multi_insect_processing/crop_video_to_images.py", line 65, in read_video
    cv2.imshow("capture", frame)
cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-uzca7qz1\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

The reason is that after the video is finished, the imshow() function of OpenCV can’t read the frame and makes an error. Solution: add judgment before imshow(). Read-only when there are frames. Exit the loop directly when there are no frames.

Error-free code:

# -*-coding:utf-8-*-
"""
File Name: read_video.py
Program IDE: PyCharm
Create File By Author: Hong
"""
import cv2


def read_video(video_path: str):
    """
    OpenCV read video widget, solve the video read error problem
    :param video_path: input the path of the video file to be read
    :return: no return value
    """
    print('Video path:', video_path)
    cap = cv2.VideoCapture(video_path)
    while cap.isOpened():
        # get a frame
        ret, frame = cap.read()
        if not ret:
            break
        cv2.imshow("capture", frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    print('Read through the video!')
    cap.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    path = r'D:\multi_insect_videos\multi_object00.mp4'
    read_video(path)

Program output results:

Video path: D:\multi_insect_videos\multi_object00.mp4
Read through the video!

Process finished with exit code 0

[Solved] Python 3.7 from collections import Iterable Error

Python 3.7 use from collections import Iterable error

Error Message:
DeprecationWarning: Using or importing the ABCs from ‘collections’ instead of from ‘collections.abc’ is deprecated, and in 3.8 it will stop working
from collections import Iterable

Solution:
Change to from collections.abc import Iterable

Python2.7 Pyinstaller Install Error: ERROR: Command errored out with exit status 1

Python2.7 pyinstaller installation error: Command erred out with exit status 1


Error reporting reason:

Installing pyinstaller directly in python2.7 will report an error. Version 4 is incompatible with python2, so we need to specify a compatible pyinstaller version number during installation. The installation commands are as follows:

pip install pyinstaller==3.2.1

Py2exe installation command

pip install py2exe==0.6.9 

[Solved] ModuleNotFoundError: No module named ‘_polyiou‘

Problem recurrence

//install swig
sudo apt-get install swig
swig -c++ -python polyiou.i
python setup.py build_ext --inplace

//report error
ModuleNotFoundError: No module named '_polyiou'

Solution:

Swig is not installed correctly. Because there are python2 and python3 in the environment, the command to install swig is modified as follows

sudo apt-get install swig
swig -c++ -python polyiou.i
python3 setup.py build_ext --inplace

[Solved] Mujoco Error: Missing path to your environment variable.

Using mujoco to report an error: missing path to your environment variable

Question:

Recently, you want to use pycharm to run the server program in the local server environment. Follow https://www.jb51.net/article/195691.htm After step configuration, try running Import mujoco_Py , error reported:

Missing path to your environment variable.  
Current values LD_LIBRARY_PATH= 
Please add following line to .bashrc: 
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/root/.mujoco/mujoco200/bin

But I’ve added environment variables to ~ /. Bashrc

Solution:

Finally, the error reporting is solved by manually adding environment variables for the current operating environment:

In the menu bar -> Run -> Edit Configurations -> Add the corresponding environment variables to environment variables

Name Value
LD_ LIBRARY_ PATH $LD_ LIBRARY_ PATH:/root/.mujoco/mujoco200/bin

 

Gunicorn timeout error: [1] [critical] worker timeout [How to Solve]

1. Problem description

In a web project built with gunicorn + flash, because the machine learning model is used, the model needs to be loaded when requesting the interface for the first time. The model is loaded quickly when running locally, so it runs normally. The application is deployed to the server using docker (the model is mounted to the container through volume), The first request to load the model takes a long time, and the following errors are reported:

[2021-09-11 07:22:33 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:12)
[2021-09-11 07:22:35 +0000] [12] [INFO] Worker exiting (pid: 12)

Gunicorn ‘green Unicorn’ is a python WSGI HTTP server for UNIX. It is a pre forked worker model transplanted from Ruby’s Unicorn project. Gunicorn server is widely compatible with various web frameworks, with simple implementation, less use of server resources and quite fast speed.

2. Cause analysis

It can be seen from the error message that gunicorn’s worker process timed out, causing the process to exit and restart
refer to the official document of gunicorn and the description shown in the figure below:

3. Solution

From the documentation on the official website, we can know that the default timeout of gunicorn is 30s. If it exceeds 30s, the worker process will be killed and restarted.

Therefore, to solve this problem, you only need to set a large timeout: gunicorn to set the timeout

gunicorn -w 2 -b 0.0.0.0:4343  manage:app --timeout 120 

Add: -- timeout 120 to gunicorn’s startup command, indicating that the timeout is set to 120 seconds. Configure the timeout in the gunicorn. Conf.py configuration file of gunicorn

workers = 4  # Define the number of processes to be opened for processing requests at the same time, adjusted appropriately according to site traffic
worker_class = "gevent" # Use the gevent library to support asynchronous processing of requests and improve throughput
bind = "0.0.0.0:8500" # Listen to IP relaxation to facilitate communication between Dockers and between Dockers and hosts
timeout = 120 # Set the timeout to 120 seconds

For more configuration of the gunicorn. Conf.py file, see the official website

[Solved] Pycharm Use pip Error: Script file ‘D:\Anaconda3\envs\pytorch\Scripts\pip-script.py‘ is not present

Problem Description:

error reporting 1: error reporting for PIP installation: script file’d:\anaconda3\envs \ pytorch\scripts\PIP script. Py ‘is not present.
error reporting 2: PIP upgrade failed: script file’d:\anaconda3\envs\pytorch\scripts\PIP script. Py’ is not present.
as shown in the following figure:


Solution:

Baidu has had the following solutions for a long time:

# Method 1: Use the command line to go to the Anconda3\Scripts\ directory and execute the command, or if it is a virtual environment, go to the \Scripts\ directory under the virtual environment

    easy_install pip # I tried this method, but it didn't work for me 
    
# Method 2: Also go to the directory and execute the following statement

    python -m ensurepip --default-pip # Perfect solution

Django framework uses error reporting exception type: templatedoesnotexist

1、 Error: templatedoesnotexist

Exception Type: TemplateDoesNotExist

 

2、 Problem analysis and solution

Problem analysis: the accessed HTML file was not found

reason:

Django directly regards the template path as an absolute path, and the HTML file cannot be found.

After viewing the project setting file, you can see the setting method of template, including an option of “dirs”,
 

Solution:

'DIRS': [os.path.join(BASE_DIR), 'templates'],

Error in PIP install BS4 under Linux

1. The error information is as follows:

$ sudo pip install bs4==0.0.1
Collecting bs4==0.0.1
  Downloading http://pip.pgw.getui.com/packages/10/ed/7e8b97591f6f456174139ec089c769f89a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz
Collecting beautifulsoup4 (from bs4==0.0.1)
  Downloading http://pip.pgw.getui.com/packages/a1/69/daeee6d8f22c997e522cdbeb59641c4d31ab120aba0f2c799500f7456b7e/beautifulsoup4-4.10.0.tar.gz (399kB)
    100% |████████████████████████████████| 409kB 11.7MB/s
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-USqeae/beautifulsoup4/setup.py", line 7, in <module>
        from bs4 import __version__
      File "bs4/__init__.py", line 36, in <module>
        raise ImportError('You are trying to use a Python 3-specific version of Beautiful Soup under Python 2. This will not work. The final version of Beautiful Soup to support Python 2 was 4.9.3.')
    ImportError: You are trying to use a Python 3-specific version of Beautiful Soup under Python 2. This will not work. The final version of Beautiful Soup to support Python 2 was 4.9.3.

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-USqeae/beautifulsoup4/

2 solution

Install beatifulsoup4 first

$ sudo  pip install beautifulsoup4==4.9.0
Collecting beautifulsoup4==4.9.0
  Downloading http://pip.pgw.getui.com/packages/2d/3e/8b2fc5d3c31c84d7209313f4059858f502f2e4a9d986693eca03fe325565/beautifulsoup4-4.9.0-py2-none-any.whl (109kB)
    100% |████████████████████████████████| 112kB 872kB/s
Collecting soupsieve<2.0 (from beautifulsoup4==4.9.0)
  Downloading http://pip.pgw.getui.com/packages/39/36/f35056eb9978a622bbcedc554993d10777e3c6ff1ca24cde53f4be9c5fc4/soupsieve-1.9.6-py2.py3-none-any.whl
Collecting backports.functools-lru-cache; python_version < "3" (from soupsieve<2.0->beautifulsoup4==4.9.0)
  Downloading http://pip.pgw.getui.com/packages/e5/c1/1a48a4bb9b515480d6c666977eeca9243be9fa9e6fb5a34be0ad9627f737/backports.functools_lru_cache-1.6.4-py2.py3-none-any.whl
Installing collected packages: backports.functools-lru-cache, soupsieve, beautifulsoup4
Successfully installed backports.functools-lru-cache-1.6.4 beautifulsoup4-4.9.0 soupsieve-1.9.6

Installing BS4

$ sudo  pip install  bs4==0.0.1
Collecting bs4==0.0.1
  Downloading http://pip.pgw.getui.com/packages/10/ed/7e8b97591f6f456174139ec089c769f89a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz
Requirement already satisfied (use --upgrade to upgrade): beautifulsoup4 in /usr/lib/python2.7/site-packages (from bs4==0.0.1)
Requirement already satisfied (use --upgrade to upgrade): soupsieve<2.0 in /usr/lib/python2.7/site-packages (from beautifulsoup4->bs4==0.0.1)
Requirement already satisfied (use --upgrade to upgrade): backports.functools-lru-cache; python_version < "3" in /usr/lib/python2.7/site-packages (from soupsieve<2.0->beautifulsoup4->bs4==0.0.1)
Installing collected packages: bs4
  Running setup.py install for bs4 ... done
Successfully installed bs4-0.0.1