Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加一个指定端口号的方法来避免端口占用 #897

Open
cnzyan opened this issue May 11, 2024 · 0 comments
Open

添加一个指定端口号的方法来避免端口占用 #897

cnzyan opened this issue May 11, 2024 · 0 comments

Comments

@cnzyan
Copy link

cnzyan commented May 11, 2024

修改 docs.py,在开头增加

import sys
import socket
import subprocess
import platform

def check_port_in_use(port):
    system = platform.system()
    print(f"尝试使用socket方式检查端口:{port}")
    check_dict ={}
    is_port_in_use = False
    
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('localhost', port))
        sock.close()
        check_dict["Socket"] = False
    except socket.error:
        #print(f"socket检查无法使用端口号{port},可能被占用")
        check_dict["Socket"] = True
        is_port_in_use = True  # 如果出现socket错误,标记端口被占用
    # 返回端口占用情况字典及是否被占用的布尔值
    return check_dict, is_port_in_use

if len(sys.argv)>2:
    port_num=sys.argv[-1]
    sys.argv.pop(2)
else:
    port_num="8008"
if not port_num.isdigit():
    port_num="8008"
if check_port_in_use(int(port_num))[1]:
    print(f"端口{port_num}被占用,尝试使用其他端口")
    for i in range(8008,8100):
        if not check_port_in_use(i)[1]:
            port_num=str(i)
            print(f"找到可用端口{i}")
            break
    if port_num=="8008":
        print("未找到可用端口,使用默认端口8008")
        port_num="8008"`

这样 启动服务可以修改为
python3 scripts/docs.py serve 端口号
来指定端口号
例如
python3 scripts/docs.py serve 8001
希望能够采纳

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant