timmy revised this gist 3 months ago. Go to revision
1 file changed, 17 insertions
find_free_port.py(file created)
| @@ -0,0 +1,17 @@ | |||
| 1 | + | import socket | |
| 2 | + | from contextlib import closing | |
| 3 | + | ||
| 4 | + | def find_free_port(): | |
| 5 | + | # 建立一個暫時的 socket 來偵測可用的 port | |
| 6 | + | with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: | |
| 7 | + | # bind 到 0 表示讓系統隨機分配一個可用的 port | |
| 8 | + | s.bind(('', 0)) | |
| 9 | + | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| 10 | + | # 回傳那個被分配到的 port 號 | |
| 11 | + | return s.getsockname()[1] | |
| 12 | + | ||
| 13 | + | # --- 在你的 Flask App 中可以這樣用 --- | |
| 14 | + | if __name__ == '__main__': | |
| 15 | + | free_port = find_free_port() | |
| 16 | + | print(f"找到一個可用的 port: {free_port}") | |
| 17 | + | app.run(host='0.0.0.0', port=free_port) | |
Newer
Older