Category Archives: Python

AttributeError: module ‘enum‘ has no attribute ‘IntFlag‘ [How to Solve]

The error details are as follows:

Traceback (most recent call last):
  File "/usr/local/bin/evo_traj", line 5, in <module>
    import re
  File "/usr/lib/python3.6/re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 62, in apport_excepthook
    if not enabled():
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 24, in enabled
    import re
  File "/usr/lib/python3.6/re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'

Original exception was:
Traceback (most recent call last):
  File "/usr/local/bin/evo_traj", line 5, in <module>
    import re
  File "/usr/lib/python3.6/re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'

Problem analysis
this problem has not occurred before. It is suspected that the python iteration version conflict is caused by the update of Ubuntu system. It is recommended to turn off the automatic update of Ubuntu to prevent such problems. It takes a long time to solve some version conflict problems.

Solution:
the query found that pythonpath was set incorrectly. The configuration left by the previous use of python2 was saved in. Bashrc, resulting in python3 unable to find the correct enum location. After commenting out the relevant statements in bashrc, clear the $pythonpath variable:

 unset PYTHONPATH
 echo $PYTHONPATH

Then it can be used normally. Pythonpath is a multi-purpose configuration in python2. It is generally no longer needed after using python3.

Python quote error: * * * keyerror: u ‘\ uxx’ [How to Solve]

Problem: urllib.quote (xxx) error after running * * * keyerror: u '\ uxx'
reason: look at XXX type: & lt; type 'unicode'>, and params in urlib.quote (params) is a string. You can only guess that the encoding of the string does not meet the requirements, so the code XXX
solution: urlib.quote (XXX. Encode ("UTF-8") or urlib.quote (STR (xxx))

Examples are as follows:

>>> import urllib
>>> xxx = u'[{"test":"Test"}]'
>>> urllib.quote(xxx)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1298, in quote
    return ''.join(map(quoter, s))
KeyError: u'\u6d4b'
>>> type(xxx)
<type 'unicode'>
>>> urllib.quote(xxx.encode("utf-8"))
'%5B%7B%22test%22%3A%22%E6%B5%8B%E8%AF%95%22%7D%5D'
>>> urllib.quote(str(xxx))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-11: ordinal not in range(128)
>>> import sys
>>> sys.setdefaultencoding('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'setdefaultencoding'
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('utf-8')
>>> urllib.quote(str(xxx))
'%5B%7B%22test%22%3A%22%E6%B5%8B%E8%AF%95%22%7D%5D'

[Solved] Python Networkx Error: Network error: random_state_index is incorrect

A few months ago, you can also use the Networkx package in Python. Recently, you rerun the previous code and report the following error

Network error: random_state_index is incorrect

Now the landlord has solved this problem. The specific steps are as follows:

First: open Anaconda prompt (Anaconda 3), demote Networkx package and decorator package, and enter the following code:

pip install --user decorator==4.3.0
pip install --user networkx==2.3

Second: turn off Anaconda prompt (Anaconda 3) and reopen Python to run without problem.

[Solved] Jupyter Notebook Start Error: Fatal error in launcher: Unable to create process using

Problem description

Previously, rename a CONDA virtual environment with the following command:

conda create -n torch --clone rl
conda remove -n rl --all

Then start jupyter from Torch virtual environment, and the following error is reported:

Fatal error in launcher: Unable to create process using
"g:\miniconda3\envs\rl\python.exe"
 "G:\miniconda3\envs\torch\Scripts\jupyter-notebook.EXE"

Reference solutions

I checked the online information and found that it was better after a mess… So I’m not sure which operation fixed the problem. What’s more certain is the last few executed commands:

pip uninstall ipython
pip uninstall jupyter
pip uninstall notebook

Or (after the above command is executed, try installing jupyter first. If the problem cannot be solved, execute the following command)

pip install pip-autoremove
pip-autoremove jupyter -y

Then install jupyter

pip install jupter

[Python] Right-click Selenium to Save the picture error: attributeerror: solution to module ‘pyscreen’ has no attribute ‘locationonwindow’

When crawling pictures with selenium module, simulate right clicking and select “save picture as” to save the picture (pyautogui module is not used)

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from time import sleep

url = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fitem%2F201202%2F18%2F20120218194349_ZHW5V.thumb.700_0.jpg&refer=http%3A%2F%2Fcdn.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633348528&t=794e58b55dfe37e5f3082568feb89783'

driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element_by_xpath('/html/body/img[1]')  

action = ActionChains(driver)  
action.move_to_element(element)  
action.context_click(element)  
action.send_keys(Keys.ARROW_DOWN)  
action.send_keys('v')  

action.perform()  
sleep(2)

driver.quit()  

When you execute the above code, you will find that you do not click the keyboard after right clicking, because the page is not controlled by selenium after right clicking. At this point, we need to use the pyautogui module, which is a module for automatically controlling the mouse and keyboard
you need to PIP download the wheel first

pip install pyautogui

Modified code:

from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
from time import sleep
import pyautogui

url = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fitem%2F201202%2F18%2F20120218194349_ZHW5V.thumb.700_0.jpg&refer=http%3A%2F%2Fcdn.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633348528&t=794e58b55dfe37e5f3082568feb89783'

driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element_by_xpath('/html/body/img[1]') 

action = ActionChains(driver) 
action.move_to_element(element) 
action.context_click(element) 
action.perform() 

pyautogui.typewrite(['v']) 
sleep(1) 
pyautogui.typewrite(['1', '.', 'j', 'p', 'g'])
pyautogui.typewrite(['enter'])

sleep(1)

driver.quit() 

The red explosion will be found after execution:

attributeerror: module ‘pyscreen’ has no attribute ‘locateonwindow’

It is actually very simple to solve this problem
we directly download the highest version 0.9.53 after PIP install pyautogui
we only need to download version 0.9.50, so this problem will not exist

pip install pyautogui==0.9.50

Just execute the code again~

The anaconda-navigator interface cannot be started, loading application, report ERROR download_api._get_url error

Anaconda3, which was originally installed, suddenly couldn’t be started today. It got stuck in the loading application interface. It was forced to uninstall and reinstall. The situation is the same. Errors are reported as follows:

C:\Users\ljw>anaconda-navigator
2021-09-08 22:24:45,500 - ERROR download_api._get_url:417
Expecting value: line 1 column 1 (char 0)

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window.py", line 499, in setup
    self.post_setup(conda_data=conda_data)
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\main_window.py", line 536, in post_setup
    self.tab_home.setup(conda_data)
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\tabs\home.py", line 169, in setup
    self.set_applications(applications, packages)
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\widgets\tabs\home.py", line 204, in set_applications
    apps = self.api.process_apps(applications, prefix=self.current_prefix)
  File "C:\ProgramData\Anaconda3\lib\site-packages\anaconda_navigator\api\anaconda_api.py", line 903, in process_apps
    versions=[vsdata.get('productVersion')],
AttributeError: 'str' object has no attribute 'get'
^C
C:\Users\ljw>anaconda-navigator
2021-09-08 22:45:03,049 - ERROR download_api._get_url:417
Expecting value: line 1 column 1 (char 0)

The reason is the same as the connection analysis above, mainly because the vscode address obtained by self._VSCODE_ENDPOINT in vscode_application_data() is wrong ( https://vscode-update.azurewebsites.net/api/update/win32-x64/stable/version ). As a result of the visit, the correct address is: https://update.code.visualstudio.com/api/update/win32-x64/stable/version

Solution: in Anaconda_ Search in api.py

        VSCODE_ENDPOINT = (
            'https://vscode-update.azurewebsites.net/api/update'
            '/{}/stable/version'.format(VSCODE_SUBDIR)
        )

Change the link to:

        VSCODE_ENDPOINT = (
            'https://update.code.visualstudio.com/api/update'
            '/{}/stable/version'.format(VSCODE_SUBDIR)
        )

Save the file and restart Anaconda navigator to solve the problem

[Solved] Error when vscode activates Python virtual environment

After executing Python – M venv myvenv to create a python virtual environment, the following error is reported when executing the script

The file D:\Tools\Python37\Scripts\Activate.ps1 could not be loaded, because running scripts is disabled on this system.

The reason is that windows prohibits unsigned scripts from running. You can solve this problem by executing the command set executionpolicy remotesigned in PowerShell.

[Solved] D2lzh_Pytorch Import error: importerror: DLL load failed while importing

Import d2lzh_Pytorch reports an error, importerror: DLL load failed while importing_ Torchtext: the specified program cannot be found.!! OMG

Guide Package

import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import sys
sys.path.append("..") 
import d2lzh_pytorch as d2l

The error is as follows:

ImportError: DLL load failed while importing _torchtext: The specified program could not be found.

The solution is as follows:

#check torch version
import torch
print(torch.__version__) #1.7.0

#Download the torchtext that corresponds to your own torch version
pip install torchtext==0.6

Perfect solution to the problem

Pytorch directly creates a tensor on the GPU error [How to Solve]

Pytoch directly creates tensors on the GPU and reports an error: Legacy constructor expectations device type: cpubut device type: CUDA was passed

General tensor creation method:

torch.Tensor(x)	

However, by default, the tensor is placed in the CPU (memory). If we want to use the GPU to train the model, we must also copy the tensor to the GPU, which will obviously save time
I’ve seen other articles before saying that tensors can be created directly on the GPU, so I’ve also made a try:

MyDevice=torch.device('cuda:0')
x = torch.LongTensor(x, device=MyDevice)

An error is reported when running the program:

legacy constructor expects device type: cpu but device type: cuda was passed

According to the error report analysis, the problem is that the device parameter cannot be passed ‘CUDA’?After checking, I found that the official answer given by pytorch is that tensor class is a subclass of tensor and cannot pass parameters to its device. There is no problem using the tensor class to build
⭐ Therefore, the code is changed as follows:

MyDevice = torch.device('cuda:0')
x = torch.tensor(x, device=MyDevice)
x = x.long()

Now, there will be no more errors.

SSL error of urllib3 when Python uploads files using Minio

Problems arise

Minio’s server always uses HTTP for access, but recently, due to business requirements, all requests have been replaced with HTTPS requests. After changing to HTTPS, this error will be reported when uploading the file: urlib3. Exceptions. Maxretryerror: httpsconnectionpool (host = ‘10.10.30.241’, port = 9000): Max retries exceeded with URL:/Facebook?Location = (caused by sslerror (sslcertverificationerror (1, ‘[SSL: Certificate_ VERIFY_ FAILED] certificate verify failed: self signed certificate (_ ssl.c:1124)’)))

Solution 1

Because I saw that the error was reported by urlib, I directly searched the urlib source code and directly modified the urlib 3 source code to solve the problem.
the modified file is: connectionpool.py

modify line 775 of connectionpool.py file:

self.cert_reqs = 'CERT_NONE'

Solution 2

The first method is solved, but it is extremely inconvenient
because you need to modify the source code every time you need to change the deployment script or reinstall it
then I went through the Minio source code and found the problem

the urliib in Minio did not turn off SSL verification. I wanted to change it here, but I thought of changing the source code here. I looked carefully and found the next parameter: http_ client

We only need to customize this parameter when creating Minio objects

    minioClient = Minio(
        '1.1.1.1:9000',
        access_key='mxxxxxxx',
        secret_key='mxxxxxxx',
        http_client=urllib3.PoolManager(
            timeout=urllib3.util.Timeout(connect=10, read=10),
            maxsize=10,
            cert_reqs='CERT_NONE',
            ca_certs= os.environ.get('SSL_CERT_FILE') or certifi.where(),
            retries=urllib3.Retry(
                total=5,
                backoff_factor=0.2,
                status_forcelist=[500, 502, 503, 504]
            )
        )
        # secure=False
    )

So far, the problem is solved

Attach Minio file to upload all codes

import logging
from minio import Minio
from minio.error import S3Error
import urllib3
import certifi
import os
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
logging.basicConfig(
    level=logging.INFO,
    filename='../mysqlbackup_up.log',
    filemode='a',
    format='%(asctime)s %(name)s %(levelname)s--%(message)s'
)



def upload_file(file_name, file_path):

    minioClient = Minio(
        '1.1.3.1:9000',
        access_key='mxxxxx',
        secret_key='mxxxxxx',
        http_client=urllib3.PoolManager(
            timeout=urllib3.util.Timeout(connect=10, read=10),
            maxsize=10,
            cert_reqs='CERT_NONE',
            ca_certs= os.environ.get('SSL_CERT_FILE') or certifi.where(),
            retries=urllib3.Retry(
                total=5,
                backoff_factor=0.2,
                status_forcelist=[500, 502, 503, 504]
            )
        )
        # secure=False
    )

    check_bucket = minioClient.bucket_exists("test")

    if not check_bucket:
        minioClient.make_bucket("test")
    try:
        logging.info("start upload file")
        minioClient.fput_object(bucket_name="test", object_name=file_name, file_path=file_path)
        logging.info("file {0} is successfully uploaded".format(file_name))
        print('success')
    except FileNotFoundError as err:
        print(err)
        logging.error('upload_failed: ' + str(err))
    except S3Error as err:
        print(err)
        logging.error("upload_failed:", err)

Decode PUP data Error when reading radar data [How to Solve]

Example of reading pup radar data official website:

Run the sample code

from cinrad.io import PUP
pup_file='Z_RADR_I_Z9591_20210901004700_P_DOR_SA_V_10_230_60.591.bin'
f = PUP(path+pup_file)
data = f.get_data()

Error 1 connection timeout: (‘connection aborted.’, timeouterror (10060, ‘because the connection party is not correct after a period of time

Solution:

Add code to the program of the path to extend the connection time threshold timeout = 100, as shown in the figure

Error reporting matrix out of range

HTTPSConnectionPool(host=‘github.com’, port=443): Max retries exceeded with url: /Unidata/MetPy/raw/v1.0.1/staticdata/airport-codes.csv (Caused by ConnectTimeoutError(< urllib3.connection.HTTPSConnection object at 0x000001EA124FA370>, ‘ Connection to github.com timed out. (connect timeout=3)’))

resolvent:

Still in the program just now, add code

            s = requests.session()
            s.keep_alive = False
            # InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised.
            # HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url
            requests.packages.urllib3.disable_warnings()
            
            response = requests.get(url, **kwargs,timeout=100,verify=False,)  ####

Error report: three library package import error

Solution:

Change relative path to absolute path


Run successfully