Python 如果端口不可用,如何停止瓶子服务器?

Python 如果端口不可用,如何停止瓶子服务器?,python,port,bottle,Python,Port,Bottle,我正在使用bottlepy开发我的应用程序。使用粘贴作为服务器 from bottle import route, run, template @route('/hello/<name>') def index(name): return template('<b>Hello {{name}}</b>!', name=name) run(host='localhost', port=8080, debug=True,

我正在使用bottlepy开发我的应用程序。使用
粘贴
作为服务器

from bottle import route, run, template

@route('/hello/<name>')
def index(name):
        return template('<b>Hello {{name}}</b>!', name=name)

run(host='localhost',
    port=8080,
    debug=True,
    reloader=True,
    server='paste')
它正在继续而不是停止,我可以添加
try…catch..
并捕获此异常并终止进程。但在此之前,我想知道,是否有任何参数,我可以通过,它会自动停止

如果我设置了
reloader=False
,那么它就工作了。是否有任何方法可以使其与
reloader=True
一起工作

我读了,并且是自动重新加载,如果文件更改,但如果端口不可用,那么它也会尝试重新启动服务器。

这个怎么样:

import socket
def is_port_in_use(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('localhost', port)) == 0
if not is_port_in_use(8080):
    run(host='localhost',
    port=8080,
    debug=True,
    reloader=True,
    server='paste')
对于python 2.7,请使用:

from contextlib import closing
import socket
def is_port_in_use(port):
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        return s.connect_ex(('localhost', port)) == 0
from contextlib import closing
import socket
def is_port_in_use(port):
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        return s.connect_ex(('localhost', port)) == 0