Category Archives: Python

[Solved] Pyinstaller packaged exe error: “failed to execute script XXX”

Recently I wrote a small interface program with PyQt5, which needs to be packaged into exe for use on other windows. At the beginning, I used python 3.7 64-bit, packaged the exe with pyinstaller, and it ran normally on a 64-bit machine. But the target computer is 32-bit, so a 32-bit exe needs to be packaged, and then the problem occurs.

Package a 32-bit exe. Although there are online tutorials that use Anaconda to generate a python’s 32-bit environment, I tried it, but it was unsuccessful. Instead, I chose to uninstall the 64-bit python. It is better to install the 32-bit python directly and still use pyinstaller to package

Although there were a few warnings during packaging, it seemed that it went smoothly. I clicked on the exe and reported “failed to execute script XXX”. I changed multiple python versions, unloaded and unloaded, and turned over a lot of information, but I didn’t solve it, so I decided to self-reliance.

As we all know, you can use this command to package exe without console:

pyinstaller -w -F xxx.py 

But in this way, there is no way to see the error, so keep the console:

pyinstaller -F xxx.py 

After packaging, the program flashed by. I opened the video on my mobile phone and recorded it (60fps). The picture quality is stale but I still can’t miss the “unable to find QtCore.dll on PATH”:

The problem should be that the PyQt library is missing. If it is missing, just make it up~ Copy this dll directly to C:\Windows\System32, and then open the exe happily, the problem is solved~….. solve……

You need to add python’s PyQt5 library path to the environment variable PATH. This time, you can really run it. I am very happy (actually I have been tossing this step for a long time), but it is estimated that PyQt5 needs to be installed on the target computer, and then Adding environment variables, although a little troublesome, can be used.

That’s how things came to an end…

 

It didn’t come to an end. I was not reconciled. Why 64-bit runs well and 32-bit loses dll. Why does the command line run normally and exe loses something? And I went to the temporary directory of the exe and looked at it. In fact, Qt5Core.dll and other libraries are all lying in it, but why did it say that it could not be found, and then I tried

1. Forcibly repackage Qt5Core.dll in the exe, this can be achieved by editing the spec file, and changing the datas is OK, no!

2. Try to adjust the running path during runtime, or add a temporary path, so that the program can recognize the dlls originally in the same directory, but no similar tutorials were found (this requirement is originally weird?)

3. Changed to another one and tried it, built a virtual machine and tried it, to rule out system differences, it didn’t work.

4. I changed to a lower version of python and tried it, but it didn’t work

5. Try to replace the packaging software. It seems that most of them are pyinstaller, as well as py_win32, cx_Freeze, etc. py_win32 seems to need to rewrite the interface, and cx_Freeze runs according to the routine and has no effect at all.

It can be seen that the title is very close. In fact, it is enough to reduce the version of PyQt5. It seems that there is no need to reduce the version of pyinstaller (3.5) as in this blog post. After packaging, it can run normally without adding environment variables, and the exe size is also reduced. Half…

At the beginning, I used PyQt5.13.0 to package 32-bit error, and it was no problem if it was reduced to 5.9.2. By the way, remember that pip installs the specified version of the library:

pip install pyqt5==5.9.2

I like to write all kinds of dependent libraries in a cmd file. When I need to install the environment, double click and it will be done.

 

To summarize:

When Pyinstaller is packaging the PyQt5 program, if it prompts that the dll file is missing, you can try to reduce the version of PyQt5, such as the combination of pyinstaller3.5 + PyQt5.9.2 (@Windows 7 x64 SP1 + python 3.7.4 x32)

[Solved] TypeError: __init__() missing 1 required positional argument: ‘on_delete’

TypeError: __init__() missing 1 required positional argument:’on_delete’ solution

 

When executing python manage.py makemigrations, an error occurs: TypeError: init() missing 1 required positional argument:’on_delete’

solution:

When defining a foreign key, you need to add on_delete=;
that is: contract = models.ForeignKey(Contract, on_delete=models.CASCADE)

The reasons are as follows:

After django is upgraded to 2.0, when the table is associated with the table, the on_delete parameter must be written, otherwise an exception will be reported:
TypeError: init() missing 1 required positional argument:’on_delete’

 

on_delete=None, # When deleting data in the associated table, the behavior of the current table and its associated field
on_delete=models.CASCADE, # Delete associated data, and delete associated with it
on_delete=models.DO_NOTHING, # Delete associated data, nothing Don’t do
on_delete=models.PROTECT, # Delete associated data and raise an error ProtectedError
# models.ForeignKey(‘Associated table’, on_delete=models.SET_NULL, blank=True, null=True)
on_delete=models.SET_NULL, # Delete associated data , The value associated with it is set to null (provided that the FK field needs to be set to be nullable, and one pair is
treated together ) # models.ForeignKey(‘associated table’, on_delete=models.SET_DEFAULT, default=’default value’)
on_delete=models .SET_DEFAULT, # Delete the associated data, and set the associated value to the default value (provided that the FK field needs to set the default value, one pair is the same)
on_delete=models.SET, # Delete associated data,
a. Set the associated value To specify the value, set: models.SET (value)
b. Set the associated value to the return value of the executable object, set: models.SET (executable object)

Since many-to-many (ManyToManyField) has no on_delete parameter, the above is only for foreign keys (ForeignKey) and one-to-one (OneToOneField)

[Solved] RuntimeError (note: full exception trace is shown but execution is paused at: <module>)

Error using multiprocessing module:

from multiprocessing import Process

def hello():
    print('hello')

p = Process(target=hello)
p.start()

Change the code to:

from multiprocessing import Process, freeze_support, set_start_method

def hello():
    print('hello')

if __name__ == '__main__':
    p = Process(target=hello)
    p.start()

Which if __name__ == '__main__':role is to protect the program entry point , when a sub-process using open Process, Python interpreter into the current module, and invoke the hello method, using a simple intuitive test:

from multiprocessing import Process, freeze_support, set_start_method

def hello():
    print('hello')

print("!!!")

if __name__ == '__main__':
    p = Process(target=hello)
    p.start()

In this code, Print ("!!" is not a hello method. Let’s see the running result:

print("!!!") was called twice!!! So before generating a new process, be sure to add if__ name__ == '__ main__':

Further, if you change print("!!!")to print(__name__), you will get the following results:

[Solved] ValueError: check_hostname requires server_hostname

Error prompt:

ERROR: Exception:
Traceback (most recent call last):
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\cli\base_command.py", line 180, in _main
    status = self.run(options, args)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\cli\req_command.py", line 204, in wrapper
    return func(self, options, args)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\commands\install.py", line 318, in run
    requirement_set = resolver.resolve(
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 127, in resolve
    result = self._result = resolver.resolve(
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 473, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 341, in resolve
    name, crit = self._merge_into_criterion(r, parent=None)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 172, in _merge_into_criterion
    if not criterion.candidates:
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\resolvelib\structs.py", line 139, in __bool__
    return bool(self._sequence)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in __bool__
    return any(self)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 129, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 30, in _iter_built
    for version, func in infos:
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 258, in iter_index_candidate_infos
    result = self._finder.find_best_candidate(
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\index\package_finder.py", line 879, in find_best_candidate
    candidates = self.find_all_candidates(project_name)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\index\package_finder.py", line 824, in find_all_candidates
    page_candidates = list(page_candidates_it)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\index\sources.py", line 134, in page_candidates
    yield from self._candidates_from_page(self._link)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\index\package_finder.py", line 783, in process_project_url
    html_page = self._link_collector.fetch_page(project_url)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\index\collector.py", line 512, in fetch_page
    return _get_html_page(location, session=self.session)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\index\collector.py", line 422, in _get_html_page
    resp = _get_html_response(url, session=session)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\index\collector.py", line 120, in _get_html_response
    resp = session.get(
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\requests\sessions.py", line 555, in get
    return self.request('GET', url, **kwargs)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_internal\network\session.py", line 449, in request
    return super().request(method, url, *args, **kwargs)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\cachecontrol\adapter.py", line 53, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 696, in urlopen
    self._prepare_proxy(conn)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 964, in _prepare_proxy
    conn.connect()
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\urllib3\connection.py", line 359, in connect
    conn = self._connect_tls_proxy(hostname, conn)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\urllib3\connection.py", line 500, in _connect_tls_proxy
    return ssl_wrap_socket(
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 432, in ssl_wrap_socket
    ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
  File "d:\python\sdk\py3.9.5\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 474, in _ssl_wrap_socket_impl
    return ssl_context.wrap_socket(sock)
  File "d:\python\sdk\py3.9.5\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "d:\python\sdk\py3.9.5\lib\ssl.py", line 997, in _create
    raise ValueError("check_hostname requires server_hostname")
ValueError: check_hostname requires server_hostname
WARNING: You are using pip version 21.1.1; however, version 21.1.3 is available.
You should consider upgrading via the 'd:\python\sdk\py3.9.5\python.exe -m pip install --upgrade pip' command.

My Python version:

solution implementation:

pip install  urllib3==1.25.11

TensorFlow Install Error: Could not load dynamic library ‘*****.dll‘; dlerror: ********.dll not found

After the installation of tensorflow2. X is successful, after running the following code:

tf.config.list_physical_devices('GPU')

There are always the following situations: (Note: there are usually multiple, only two here are shown here)

Could not load dynamic library ‘cublas64_ 10.dll’; dlerror: cublas64_ 10.dll not found

Could not load dynamic library ‘cudnn64_ 7.dll’; dlerror: cudnn64_ 7.dll not found

Solution:

Download the corresponding DLL file and put it into the folder C: Windows: system32.

The problem was solved successfully Pro test (valid)

So the key to the problem, where to download these DLL files, rest assured, this article will provide you with all the required DLL files.

Crawler overtime error socket.timeout: timed out/NameError: name ‘socket‘ is not defined

Question 1: socket. Timeout: timed out

Source code:

import urllib.request#Get a get request

import urllib.parse #Get a pos request

import urllib.error
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
data1 = urllib.request.Request("http://httpbin.org/post", headers=headers)

response = urllib.request.Request("http://httpbin.org/get", headers=headers)
response1 = urllib.request.urlopen(response, timeout=0.01)
# response1 = urllib.request.urlopen(response)
print(response1.read().decode("utf-8"))

Abnormal operation result:

Traceback (most recent call last):
  File "D:\PycharmProjects\pythonProject\douban\test1\testurllib.py", line 53, in <module>
    response1 = urllib.request.urlopen(response, timeout=0.01)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 517, in open
    response = self._open(req, data)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 534, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 1375, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 1350, in do_open
    r = h.getresponse()
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1345, in getresponse
    response.begin()
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 307, in begin
    version, status, reason = self._read_status()
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 268, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\socket.py", line 704, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

Process finished with exit code 1

Question 2: NameError: name ‘socket’ is not defined

Source code:


import urllib.request#Get a get request

import urllib.parse #Get a pos request
import urllib.error
try:
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
    # data1 = urllib.request.Request("http://httpbin.org/post", headers=headers)

    response = urllib.request.Request("http://httpbin.org/get", headers=headers)
    response1 = urllib.request.urlopen(response, timeout=0.01)
    print(response1.read().decode("utf-8"))

except socket.timeout as e:
# except Exceptio as e:
# except urllib.error.URLError as e:##error socket.timeout: timed out
    print("time out!")

Abnormal operation result:

Traceback (most recent call last):
  File "D:\PycharmProjects\pythonProject\douban\test1\temp.py", line 19, in <module>
    response1 = urllib.request.urlopen(response, timeout=0.01)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 517, in open
    response = self._open(req, data)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 534, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 1375, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 1350, in do_open
    r = h.getresponse()
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1345, in getresponse
    response.begin()
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 307, in begin
    version, status, reason = self._read_status()
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 268, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Users\lord\AppData\Local\Programs\Python\Python39\lib\socket.py", line 704, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\PycharmProjects\pythonProject\douban\test1\temp.py", line 22, in <module>
    except socket.timeout as e:
NameError: name 'socket' is not defined

Solution:

Refer to the network resources, delete and install Python again, and still report an error.

By introducing socket library, problem one and problem two are solved.

import socket    ##Introducing the socket library

Correct code:

import socket ## Introduce the socket library

import urllib.request # Get a get request

import urllib.parse # Get a pos request
import urllib.error

try:
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'}
    # data1 = urllib.request.Request("http://httpbin.org/post", headers=headers)

    response = urllib.request.Request("http://httpbin.org/get", headers=headers)
    response1 = urllib.request.urlopen(response, timeout=0.01)
    print(response1.read().decode("utf-8"))

except socket.timeout as e:
# except Exceptio as e:##normal
# except urllib.error.URLError as e:## error socket.timeout: timed out
    print("time out!")

Results of correct operation:

time out!

Process finished with exit code 0

Conclusion:

If try/except statement is not used, the program will report error a
a try/except statement has been added. It should be noted that the exception name of except should correspond to a. the error “NameError: name ‘socket’ is not defined” is reported here because the socket library is not imported.

[Solved] YOLOv5 Model training error: TypeError: new(): invalid data type ‘str’

After modifying the anchors in yolov5s.yaml, I made an error report when I retrained. After carefully looking at the numbers in “[]”, I found that the reason was as follows:
the number in “[]” 👇 Here is the original configuration file

👇 This is my revised version of

because of the lack of “,” leading to continuous error reporting, we must be more careful and encourage each other

[Solved] Tensorflow cuda Error: Could not load dynamic library ‘libcudart.so.11.0‘; dlerror: libcudart.so.11.0:

Dlerror: libcudart. So. 11.0: problem solving

First find your computer path

/usr/local/cuda/lib64

Check your CUDA version
. According to the above figure, I find that my computer’s CUDA version is 10.0, so I will report an error at runtime. At this time, there are two solutions.

Scheme 1

If you force the CUDA environment of the local computer to be the running CUDA environment, there may be problems, which I haven’t tried.

cd /usr/local/cuda/lib64/
sudo ln -sf libcudart.so.10.0 libcudart.so.11.0

Scheme 2

Installing dynamic CUDA environment in CONDA environment

conda install tensorflow-gpu cudatoolkit=11.0

Failed to establish a new connection: [winerror 10048] in the requests thread pool, the interface is called circularly to get the datagram error

To solve the problem that in the requests thread pool, loop call the interface to get data and report an error failed to establish a new connection: [winerror 10048] generally, each socket address (Protocol/network address/port) is only allowed to be used once

My code first

import json
import csv
from threadpool import ThreadPool
import threadpool
from threadpool import makeRequests
import time
import random
with open('all_balance.csv','r') as f:
    list1 = csv.reader(f)
    list1 = list(list1)
def load_data(name):
    while True:
        Payload = {
          "id": 0,
          "jsonrpc": "2.0",
          "method": "Filecoin.StateGetActor",
          "params":
          [name[0],[{'/': 'bafy2bzaceazzbdegiso5c4tsjipxjmdabpk5uamj6khzhuwycb4bjeafbhaeo'}, {'/': 'bafy2bzacea4pnuzojwownzajhjdlqitt4wodbvgmhhfc4dujqdkjz3lgl6sac'}, {'/': 'bafy2bzacecjsgkjrcg6bejnqbvm2lktrhxpiazrqwfppueijfzte2bf2kwx42'}, {'/': 'bafy2bzaceaeglquy7h5i6tobxqikaqh2onzvhdjzdhpdneo47grs3qdvvbzc6'}, {'/': 'bafy2bzacea2knbqirjgw7rsfrydo6gfams6wnbpfdrvxhasuo6obqipn4zoco'}, {'/': 'bafy2bzacecmfiu5w7gpuhvdudqpd4qvwng2wokoj6mqydismrujcobgtcunxe'}, {'/': 'bafy2bzacec5mzv2jqqd7k2ripfddlsjv5k2eq52tihjpbtjok37p5hkxep2za'}, {'/': 'bafy2bzacedqyr6oufui2plsbykvevrioa6ukuviyb4i5iz5mq34xxq3gzlz32'}, {'/': 'bafy2bzacecled7zvadjt2jjn354pfhyga22apgqeh5c3ig3vv62tqb6rujsxk'}, {'/': 'bafy2bzacecfyxsfr445b6cvlxnl2p53twzfw4fjqy67bg6nioopb5apa6zb62'}, {'/': 'bafy2bzacech6xyahzbhyyjjd747cyzpllgx4abksncyidxpuxg7hsm2gydxw6'}, {'/': 'bafy2bzaceaisnevf7cpht6cmiwg2l63cqxi5jqyrinjsmdqyvax3delxnj4gg'}]]}
        headers = {"Content-Type": "application/json"}`

        respon = requests.post('http://********:1248/rpc/v0',headers=headers, data=json.dumps(Payload))

        if respon.status_code == 200:
            if respon.json().get('result'):
                print(name[0],int(respon.json()['result']['Balance'])/10**18)
                with open('all_balance_6_24.csv', 'a', encoding='utf-8', newline='') as f:
                    writer = csv.writer(f)
                    writer.writerow([name[0], int(respon.json()['result']['Balance'])/10**18])
                return
        else:
            print(respon.status_code)
            print(respon.text)
            time.sleep(20)
tasks = threadpool.makeRequests(load_data, [list1[i] for i in range(1, 488013)])
pool = threadpool.ThreadPool(100)
for task in tasks:
    pool.putRequest(task)
pool.wait()

Error code

Traceback (most recent call last):
  File "E:\project\chain\lib\site-packages\threadpool.py", line 158, in run
    result = request.callable(*request.args, **request.kwds)
  File "E:\project\chain\chain_main_get_state.py", line 22, in load_data
    respon = requests.post('http://10.0.6.22:1248/rpc/v0',headers=headers, data=json.dumps(Payload))
  File "E:\project\chain\lib\site-packages\requests\api.py", line 119, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "E:\project\chain\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "E:\project\chain\lib\site-packages\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "E:\project\chain\lib\site-packages\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "E:\project\chain\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='10.0.6.22', port=1248): Max retries exceeded with url: /rpc/v0 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000028BAE472C40>: Failed to establish a new connection: [WinError 10048] 通常每个套接字地址(协议/网络地址/端口)只允许使用一次。'))

Because it’s multithreading, the so-called shutdown of Python process is not the way I want. Finally, I find an effective way to test the effectiveness:

use regedit command to access HKEY_ LOCAL_ Machine/system/currentcontrolset/services/TCPIP/parameters registry subkey and create a new reg named tcptimedwaitdelay_ DWORD value. Set this value to decimal 30, which is hexadecimal 0x0000001E. This value sets the wait time to 30 seconds</ Code>
access HKEY with regedit command_ LOCAL_ Machine/system/currentcontrolset/services/TCPIP/parameters registry subkey and create a new reg named maxuserport_ DWORD value. Stop and restart the system. Default: no recommendation: at least 32768 decimal

When I called the interface, using the command-line tool netstat – N, I found that nearly 4000 connections to the IP address of the target computer running the interface were in time_ In wait state, you can increase the default maxuserport setting and decrease the tcptimedwaitdelay setting at the same time, so that the client anonymous port will not be exhausted. For example, you can set maxuserport to 20000 and tcptimedwaitdelay to 30. A lower tcptimedwaitdelay setting means that the socket is in time_ The waiting time in wait state is shorter. A higher maxuserport setting means that you can put more sockets in time_ Wait status