如何清除目标端口上的进程 运行?

How can I clear the process running on my target port?

我一直在关注 this article,试图从头开始创建我的第一个 Flask API。我不得不在我的工作中更新我的电脑,我认为我事先没有成功关闭终端。

当我现在尝试从我项目的主目录 运行 我的应用程序时,在标题为“使用 Flask 创建 RESTful 端点”的部分中,我得到一个长堆栈跟踪以结尾这个:

  File "/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 466, in server_bind
    self.socket.bind(self.server_address)
OSError: [Errno 48] Address already in use

其他类似的问题表明这是由于另一个进程使用了​​我正在尝试访问的端口。为了解决这个问题,我使用了命令:

ps -fA | grep python

哪个returns:

501 12797 12759   0 11:15PM ??         0:03.97 /Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Renderer).app/Contents/MacOS/Code Helper (Renderer) --ms-enable-electron-run-as-node /Users/nfeldman1995/.vscode/extensions/ms-python.vscode-pylance-2021.12.0/dist/server.bundle.js --cancellationReceive=file:50e28be741e040fa2f7efc8dbdcf8a4ca200512639 --node-ipc --clientProcessId=12759
501 13126 12421   0 11:30PM ttys000    0:00.00 grep python

这就是我觉得很困惑的地方。其他文章表明我应该看到一行输出如下:

 502 89332 12877 0 3:40PM ttys00 0:00.15 python -m SimpleHTTPServer

但是,此输出中似乎没有任何内容是 运行ning“SimpleHTTPServer”,所以我不知道要终止哪个进程。我已经尝试使用命令 kill <process#> 终止其他两个任务,但这并没有解决问题。

转到 localhost:5000(我试图定位的端口)给我一个 404 错误。

更新:这是 lsof -i :5000

的输出
COMMAND     PID         USER   FD   TYPE            DEVICE SIZE/OFF NODE NAME
ControlCe 13218 nfeldman1995   27u  IPv4 0xdf2d97d6ad526f5      0t0  TCP *:commplex-main (LISTEN)
ControlCe 13218 nfeldman1995   28u  IPv6 0xdf2d97d52942a1d      0t0  TCP *:commplex-main (LISTEN)

我再次尝试 运行ning kill -9 13218 和 运行ning 我的应用程序,但出现了同样的错误。 运行 lsof,然后终止进程(或者我认为如此),然后再次 运行ning lsof 似乎表明不断创建新进程。 (使用不同的进程 ID 号)。

这是我的 bootstrap.sh 文件,应 Jon 的要求:

#!/bin/sh
export FLASK_APP=./cashman/index.py
source $(pipenv --venv)/bin/activate
flask run -h 0.0.0.0

您可以使用 lsof 列出进程、它们的 PID 和它们正在侦听的 TCP 端口,使用如下命令:

sudo lsof -iTCP -sTCP:LISTEN -P -n

较新版本的 macOS 上端口 5000 的问题是 AirPlay 使用它;这就是为什么您会看到“ControlCenter”在端口上侦听的原因。要摆脱它,请进入系统设置并关闭“AirPlay 接收器”或类似的东西(我不能说得很清楚;我现在在一台太旧的电脑上)。谷歌搜索“macos port 5000”出现了几次点击。