Python socket.error: [Errno 48] 地址已被使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19071512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:43:58  来源:igfitidea点击:

socket.error: [Errno 48] Address already in use

pythonmacossimplehttpserver

提问by irm

I'm trying to set up a server with python from mac terminal.

我正在尝试从 mac 终端使用 python 设置服务器。

I navigate to folder location an use:

我导航到文件夹位置并使用:

python -m SimpleHTTPServer

But this gives me error:

但这给了我错误:

socket.error: [Errno 48] Address already in use

I had previously open a connection using the same command for a different website in a different location in my machine.

我之前曾使用相同的命令为我机器中不同位置的不同网站打开连接。

采纳答案by Martijn Pieters

You already have a process bound to the default port (8000). If you already ran the same module before, it is most likely that process still bound to the port. Try and locate the other process first:

您已经有一个绑定到默认端口 (8000) 的进程。如果您之前已经运行过相同的模块,则该进程很可能仍然绑定到该端口。首先尝试定位另一个进程:

$ ps -fA | grep python
  501 81651 12648   0  9:53PM ttys000    0:00.16 python -m SimpleHTTPServer

The command arguments are included, so you can spot the one running SimpleHTTPServerif more than one pythonprocess is active. You may want to test if http://localhost:8000/still shows a directory listing for local files.

包括命令参数,因此SimpleHTTPServer如果有多个python进程处于活动状态,您可以发现正在运行的那个。您可能想要测试是否http://localhost:8000/仍显示本地文件的目录列表。

The second number is the process number; stop the server by sending it a signal:

第二个数字是进程号;通过发送信号停止服务器:

kill 81651

This sends a standard SIGTERMsignal; if the process is unresponsive you may have to resort to tougher methods like sending a SIGKILL(kill -s KILL <pid>or kill -9 <pid>) signal instead. See Wikipedia for more details.

这会发送一个标准SIGTERM信号;如果进程没有响应,您可能不得不求助于更严格的方法,例如发送SIGKILL(kill -s KILL <pid>kill -9 <pid>) 信号。有关详细信息,请参阅维基百科

Alternatively, run the server on a differentport, by specifying the alternative port on the command line:

或者,通过在命令行上指定备用端口,在不同的端口上运行服务器:

$ python -m SimpleHTTPServer 8910
Serving HTTP on 0.0.0.0 port 8910 ...

then access the server as http://localhost:8910; where 8910can be any number from 1024 and up, provided the port is not already taken.

然后访问服务器http://localhost:8910;where8910可以是 1024 及以上的任何数字,前提是该端口尚未被占用。

回答by Chris Johnson

You can also serve on the next-highest available port doing something like this in Python:

您还可以在下一个最高可用端口上提供服务,在 Python 中执行以下操作:

import SimpleHTTPServer
import SocketServer

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

port = 8000
while True:
    try:
        httpd = SocketServer.TCPServer(('', port), Handler)
        print 'Serving on port', port
        httpd.serve_forever()
    except SocketServer.socket.error as exc:
        if exc.args[0] != 48:
            raise
        print 'Port', port, 'already in use'
        port += 1
    else:
        break

If you need to do the same thing for other utilities, it may be more convenient as a bash script:

如果您需要为其他实用程序做同样的事情,作为 bash 脚本可能更方便:

#!/usr/bin/env bash

MIN_PORT=${1:-1025}
MAX_PORT=${2:-65535}

(netstat -atn | awk '{printf "%s\n%s\n", , }' | grep -oE '[0-9]*$'; seq "$MIN_PORT" "$MAX_PORT") | sort -R | head -n 1

Set that up as a executable with the name get-free-portand you can do something like this:

将其设置为具有名称的可执行文件,get-free-port您可以执行以下操作:

someprogram --port=$(get-free-port)

That's not as reliable as the native Python approach because the bash script doesn't capture the port -- another process could grab the port before your process does (race condition) -- but still may be useful enough when using a utility that doesn't have a try-try-again approach of its own.

这不像本地 Python 方法那么可靠,因为 bash 脚本不捕获端口——另一个进程可以在你的进程执行之前获取端口(竞争条件)——但在使用不使用的实用程序时仍然可能足够有用t 有自己的再试方法。

回答by Snail

Simple solution:

简单的解决办法:

  1. Find the process using port 8080:

    sudo lsof -i:8080

  2. Kill it:

    kill XXXX

  1. 使用 port 查找进程8080

    sudo lsof -i:8080

  2. 杀了它:

    kill XXXX

回答by Mark Chapel

By the way, to prevent this from happening in the first place, simply press Ctrl+Cin terminal while SimpleHTTPServer is still running normally. This will "properly" stop the server and release the port so you don't have to find and kill the process again before restarting the server.

顺便说一句,首先要防止这种情况发生,只需在 SimpleHTTPServer 仍在正常运行时在终端中按Ctrl+即可C。这将“正确”停止服务器并释放端口,因此您不必在重新启动服务器之前再次查找并终止该进程。

(Mods: I did try to put this comment on the best answer where it belongs, but I don't have enough reputation.)

(Mods:我确实尝试将此评论放在它所属的最佳答案上,但我没有足够的声誉。)

回答by candy_man

Use

 sudo lsof -i:5000

This will give you a list of processes using the port if any. Once the list of processes is given, use the id on the PID column to terminate the process use

这将为您提供使用该端口的进程列表(如果有)。给出进程列表后,使用 PID 列上的 id 终止进程使用

 kill 379 #use the provided PID

回答by PoisonIvee

I am new to Python, but after my brief research I found out that this is typical of sockets being binded. It just so happens that the socket is still being used and you may have to wait to use it. Or, you can just add:

我是 Python 新手,但经过我的简短研究,我发现这是绑定套接字的典型特征。碰巧套接字仍在使用中,您可能需要等待才能使用它。或者,您可以添加:

tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

This should make the port available within a shorter time. In my case, it made the port available almost immediately.

这应该使端口在更短的时间内可用。就我而言,它几乎立即使端口可用。

回答by user3305074

Just in case above solutions didn't work:

以防万一上述解决方案不起作用:

  1. Get the port your process is listening to:

    $ ps ax | grep python

  2. Kill the Process

    $ kill PROCESS_NAME

  1. 获取您的进程正在侦听的端口:

    $ ps ax | 蟒蛇

  2. 杀死进程

    $杀死PROCESS_NAME

回答by Thiago Farias

I have a raspberry pi, and I am using python web server (using Flask). I have tried everything above, the only solution is to close the terminal(shell)and open it again. Or restart the raspberry pi, because nothing stops that webserver...

我有一个树莓派,我正在使用 python web 服务器(使用 Flask)。我已经尝试了以上所有方法,唯一的解决方案是关闭终端(shell)并再次打开它。或者重新启动 raspberry pi,因为没有什么可以阻止该网络服务器...

回答by Aditya

Simple one line command to get rid of it, type below command in terminal,

简单的一行命令来摆脱它,在终端中输入以下命令,

ps -a

This will list out all process, checkout which is being used by Python and type bellow command in terminal,

这将列出 Python 正在使用的所有进程,结帐并在终端中键入 bellow 命令,

kill -9 (processID) 

For example kill -9 33178

例如 kill -9 33178

回答by Michael Schmid

You can allow the server to reuse an address with allow_reuse_address.

您可以允许服务器使用allow_reuse_address.

Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.

服务器是否允许重用地址。这默认为False,并且可以在子类中设置以更改策略。

import SimpleHTTPServer, SocketServer
PORT = 8000
httpd = SocketServer.TCPServer(("", PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.allow_reuse_address = True
print "Serving at port", PORT
httpd.serve_forever()