如何在指定时间后结束线程?
我有这个 Python 脚本,它只是启动线程来侦听本地主机上的某些端口。
#!/usr/bin/python3
import socket
import threading
import concurrent.futures
threads = []
def listen_on_port(port):
HOST = '' # Symbolic name meaning all available interfaces
PORT = int(port) # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print(addr,conn)
def main(ports):
with concurrent.futures.ThreadPoolExecutor() as executor:
for port in ports:
executor.submit(listen_on_port,port)
if __name__ == '__main__':
main(ports=[50010,50020,50030])
当我运行此脚本时,它会按预期侦听端口。我使用此脚本来测试防火墙规则是否允许这些端口上的连接。在另一个系统上,我执行 nc -zv my-host 50010 ,并且线程正在侦听端口 50010 终止,这就是我想要的。
但是,我想做出两项改进:1)让线程在 X 秒后死亡,2)像守护进程一样在后台运行线程,以便我的脚本将退出并保持线程运行。
我怎样才能实现这个目标?
I have this Python script that just starts up threads to listen on some ports on the localhost.
#!/usr/bin/python3
import socket
import threading
import concurrent.futures
threads = []
def listen_on_port(port):
HOST = '' # Symbolic name meaning all available interfaces
PORT = int(port) # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print(addr,conn)
def main(ports):
with concurrent.futures.ThreadPoolExecutor() as executor:
for port in ports:
executor.submit(listen_on_port,port)
if __name__ == '__main__':
main(ports=[50010,50020,50030])
When I run this script it listens on the ports as expected. I use this script to test that the firewall rules are allowing connections on those ports. And on another system I execute nc -zv my-host 50010
and the thread is listening on port 50010 terminates, which is what I want.
But, I would like to make two improvements: 1) have the threads die after X seconds, 2) Run the threads in the back ground like daemons so that my script will exit and leave the threads running.
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您实际上并不想做(2)。您可以将后台事务留给 shell,而不必担心代码中的情况。这意味着您可以像这样编写代码:
然后像这样运行它:
如果您确实想处理代码中的后台,那么最好使用简单的
os.fork
而不是daemonize
模块,因为您的目标并不是真正编写守护进程;你想要一些你希望写入你的终端的东西。这可能看起来像这样:运行该代码(并从另一个终端连接到侦听端口)看起来像这样:
如果让侦听器超时,它看起来像:
I would like to suggest that you don't really want to do (2). You can leave backgrounding things to your shell, and not worry about that in your code. That means you can write your code like this:
And then run it like:
If you really want to handle backgrounding in your code, you're probably better off with simple
os.fork
instead of thedaemonize
module, since your goal isn't really to write a daemon; you want something that you expect to write to your terminal. That might look like this:Running that code (and connecting to the listening ports from another terminal) looks like this:
If you let the listeners time out, it looks like: