Category Archives: Python

[Solved] selenium Error: ERROR:ssl_client_socket_impl.cc(962)] handshake failed; returned -1, SSL

Solution:
This error occurs due to an unsafe address error, a loop error is reported, and the program is terminated. With a –ignore-certificate-errors parameter, those certificate errors are ignored, as follows:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--ignore-certificate-errors')
driver = webdriver.Chrome(options=chrome_options)

 

[Solved] Linux OS python Script Error: smtplib has no attribute SMTP_SSL

foreword

After configuring the linux server environment, run the python script and find that the smtplib module reports an error, but not on windows, the error is as follows:

linux  module 'smtplib' has no attribute 'SMTP_SSL'

configure

  • Centos7
  • Python3.7

reason

Find the source code of smtplib.SMTP_SSL and find that the SMTP_SSL class is only established when have_ssl is True, and the have_ssl variable requires ssl dependency to be True, then the problem is found, there is no ssl dependency on linux

solution

  • Install ssl dependencies
yum install openssl openssl-devel
  • Verify that the installation was successful, check the version
openssl version -a
  • Enter your python3.7 directory, for example, my python-3.7.6.tgz file is decompressed and placed in the /usr/tgz/python/Python-3.7.6 directory, enter the Modules folder under the file, some versions is the Module file
cd /usr/tgz/python/Python-3.7.6
cd Modules
  • Modify the Setup file, the changes are as follows, and uncomment the 5 lines of code at more than 200 lines
vim Setup

Press ESC, :wq, Enter and save and exit

  • Return to the previous directory, that is, the python3.7 directory, and reinstall python
cd ..
make && make install
  • Run the code, problem solved

[Solved] Pytorch Error: PytorchStreamReader failed reading zip archive failed finding central directory

Pytoch reports an error:

PytorchStreamReader failed reading zip archive: failed finding central directory

Error reporting position

An error is reported if the pre training model is not downloaded

resnet101 = torchvision.models.resnet101(pretrained=True)

Solution:

Delete the file C:\Users\Username/.cache\torch\hub\checkpoints.pth

[Solved] Pytorch Error: PytorchStreamReader failed reading zip archive failed finding central directory

Pytoch reports an error: pytochstreamreader failed reading zip archive: failed finding central directory

Error reporting position

An error is reported if the pre training model is not downloaded

resnet101 = torchvision.models.resnet101(pretrained=True)

Solution:

Download the files from the above URL and put them in the location of the path behind to replace the weights that have not been downloaded

[Solved] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection…

USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: The devices connected to the system are not functioning.

When executing automated tests in python + selenium + pytest, I encountered the following error.

[25612:15512:0220/162104.300:ERROR:device_event_log_impl.cc(211)] [16:21:04.299] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection:
 The devices connected to the system are not functioning.(0x1F)

At present, the reason has not been found and can only be solved by violence:

Add the following options when starting chrome:

option = webdriver.chromeOptions()

# Prevent printing some useless logs
option.add_experimental_option("excludeSwitches", ['enable-automation', 'enable-logging'])
driver = webdriver.Chrome(chrome_options=option)

 

Supplement

For this statement

driver = webdriver.Chrome(chrome_options=option)

For chrome browsers, chrome_options=option, preferably written as options=option, that is:

driver = webdriver.Chrome(options=option)

Or you’ll see it in terminal

DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(chrome_options=option)

[Solved] celery Startup Error: kombu.exceptions.VersionMismatch: Redis transport requires redis-py versions 3.2.0 or later. You have 2.10.6

Error when starting celery:

kombu.exceptions.VersionMismatch: Redis transport requires redis-py versions 3.2.0 or later. You have 2.10.6

The reason is that my redis version is too low and incompatible with kombu. But I won’t touch my redis
uninstall the current celery, download the 4.1.0 version of celery (kombu will be updated during installation), and then start it again. An error is reported:

pip install Celery==4.1.0
error:
KeyError: 'async'

The problem is that version 4.1.0 of celery is incompatible with python3.6.9, so replace it with version 4.1.1 of celery

pip install Celery==4.1.0

Start celery again:

celery -A celery_task.main worker -l info

Done!

 

[Solved] pytorch loss.backward() Error: RuntimeError: Function AddBackward0 returned an invalid gradient at index 1…

How to Solve pytorch loss.backward() Error

The specific errors are as follows:

In fact, the error message makes it clear that the error is caused by device inconsistency in the backpropagation process.
In the code, we first load all input, target, model, and loss to the GPU via .to(device). But when calculating the loss, we initialize a loss ourselves
loss_1 = torch.tensor(0.0)
This way by default loss_1 is loaded on the CPU.
The final execution loss_seg = loss + loss_1
results in the above error for loss_seg.backward().

Modification method:
Modify
loss_1 = torch.tensor(0.0)
to
loss_1 = torch.tensor(0.0).to(device)
or
loss_1 = torch.tensor(0.0).cuda()

[Solved] Python Error: asyncio RuntimeError: This event loop is already running

In case of an error, the following diagram is given:

Solution:

# download nest_asyncio
pip3 install nest_asyncio

Add the following two lines at the beginning of the asynchronous collaboration code, or in the code:

import nest_asyncio

nest_asyncio.apply()

After consulting the data, it is found that using the Jupiter notebook environment, it is connected to the IPython kernel, and the IPython kernel itself runs on the event loop, while asyncio does not allow nesting of its event loop, so the error message as shown in the above figure will appear.

nest_asyncio exists as a patch for asynchronous operations.

[Solved] awtk scons Error: unsupported pickle protocol: 4

Error Messages:

scons
scons: Reading SConscript files …
scons: done reading SConscript files.
scons: Building targets …
scons: * [SConstruct] ValueError : unsupported pickle protocol: 4
scons: building terminated because of errors.

The reason for this is probably that the python version is different.

You can find out. I am working on an awtk project. I run it on PC and copy it to Ubuntu. This is the reason for compilation.

Solution:

Delete the .sconsign.dblite file in the root directory of your project.

 

tensorflow2.3 InvalidArgumentError: jpeg::Uncompress failed [How to Solve]

When training your own dataset, you often report errors:

tensorflow2.3 InvalidArgumentError: jpeg::Uncompress failed
[[{{node decode_image/DecodeImage}}]] [Op:IteratorGetNext]

 

Solution:
check whether the picture is damaged before training:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import os


num_skipped = 0
for folder_name in ("Fruit apples", "Fruit bananas", "Fruit oranges"):
    folder_path = os.path.join(".\data\image_data", folder_name)
    for fname in os.listdir(folder_path):

        fpath = os.path.join(folder_path, fname)

        try:
            fobj = open(fpath, mode="rb")
            is_jfif = tf.compat.as_bytes("JFIF") in fobj.peek(10)
            
        finally:
            fobj.close()

        if not is_jfif:
            num_skipped += 1
            # Delete corrupted image
            os.remove(fpath)

print("Deleted %d images" % num_skipped)

Delete the damaged picture and train again to solve the problem
if an error is prompted again, use:

# Determine if an image is corrupt from local
def is_valid_image(path):
    '''
    Check if the file is corrupt
    '''
    try:
        bValid = True
        fileObj = open(path, 'rb')  # Open in binary form
        buf = fileObj.read()
        if not buf.startswith(b'\xff\xd8'): # whether to start with \xff\xd8
            bValid = False
        elif buf[6:10] in (b'JFIF', b'Exif'): # ASCII code of "JFIF"
            if not buf.rstrip(b'\0\r\n').endswith(b'\xff\xd9'): # whether it ends with \xff\xd9
                bValid = False
        else:
            try:
                Image.open(fileObj).verify()
            except Exception as e:
                bValid = False
                print(e)
    except Exception as e:
        return False
    return bValid
  
 num_skipped = 0
for folder_name in ("fruit-apple", "fruit-banana", "fruit-orange"):
    #os.path.join() joins two or more pathname components
    folder_path = os.path.join(". \data\image_data", folder_name)
    # os.listdir(path) lists the subdirectories under this directory
    for fname in os.listdir(folder_path):
        fpath = os.path.join(folder_path, fname)
        flag1 = is_valid_image(fpath)
        if not flag1:
            print(flag1)
            print(fpath)#Print the path and name of the error file
 

Adjust the error file and train again to solve the problem.