auto_port()支持多线程;支持查找用完端口

This commit is contained in:
g1879 2023-10-25 20:00:28 +08:00
parent 2939e4d42b
commit ab1f85d192
4 changed files with 22 additions and 10 deletions

View File

@ -6,7 +6,7 @@
from json import dumps, loads
from queue import Queue, Empty
from threading import Thread, Event
from time import perf_counter
from time import perf_counter, sleep
from requests import get
from websocket import WebSocketTimeoutException, WebSocketException, WebSocketConnectionClosedException, \
@ -84,6 +84,7 @@ class ChromiumDriver(object):
if timeout is not None and perf_counter() > timeout:
return {'error': {'message': 'timeout'}}
sleep(.02)
continue
except Exception:

View File

@ -4,7 +4,9 @@
@Contact : g1879@qq.com
"""
from pathlib import Path
from shutil import rmtree
from tempfile import gettempdir, TemporaryDirectory
from threading import Lock
from .options_manage import OptionsManager
from .._commons.tools import port_is_using, clean_folder
@ -471,24 +473,34 @@ class ChromiumOptions(object):
class PortFinder(object):
used_port = []
used_port = {}
def __init__(self):
self.tmp_dir = Path(gettempdir()) / 'DrissionPage' / 'TempFolder'
self.tmp_dir.mkdir(parents=True, exist_ok=True)
if not PortFinder.used_port:
clean_folder(self.tmp_dir)
self._lock = Lock()
def get_port(self):
"""查找一个可用端口
:return: 可以使用的端口和用户文件夹路径组成的元组
"""
for i in range(9600, 19800):
if i in PortFinder.used_port or port_is_using('127.0.0.1', i):
continue
with self._lock:
for i in range(9600, 19600):
if i in PortFinder.used_port:
continue
elif port_is_using('127.0.0.1', i):
PortFinder.used_port[i] = None
continue
path = TemporaryDirectory(dir=self.tmp_dir).name
PortFinder.used_port[i] = path
return i, path
path = TemporaryDirectory(dir=self.tmp_dir)
PortFinder.used_port.append(i)
return i, path.name
for i in range(9600, 19600):
if port_is_using('127.0.0.1', i):
continue
rmtree(PortFinder.used_port[i], ignore_errors=True)
return i, TemporaryDirectory(dir=self.tmp_dir).name
raise OSError('未找到可用端口。')

View File

@ -127,7 +127,7 @@ class ChromiumOptions(object):
class PortFinder(object):
used_port: list = ...
used_port: dict = ...
@staticmethod
def get_port() -> Tuple[int, str]: ...

View File

@ -384,7 +384,6 @@ class ChromiumBase(BasePage):
self.wait.load_complete()
if self._scroll is None:
self._scroll = ChromiumPageScroll(self)
self.set.scroll.smooth(False)
return self._scroll
@property