Plotly中fig.show()执行后Python进程残留问题求助
解决Plotly fig.show()残留Python进程的问题
问题背景
将Plotly地图代码写成.py脚本而非Notebook时,执行python myscript.py后浏览器能正常打开地图页面,但主Python进程立即退出,多次运行后系统中残留大量python3.11进程并占用CPU。核心代码如下:
fig = px.scatter_mapbox(post_df, lat="latitude", lon="longitude", zoom=3, height=300) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.show()
问题根源
Plotly的fig.show()在非交互式环境(如普通.py脚本)下,默认会启动一个后台HTTP服务器子进程来提供地图页面的访问服务。主进程退出时未正确终止这个子进程,导致其变成孤儿进程持续占用系统资源。
解决方案
1. 生成HTML文件(完全避免子进程)
放弃临时HTTP服务器,直接将地图渲染为HTML文件并自动打开,彻底消除进程残留问题:
import plotly.express as px fig = px.scatter_mapbox(post_df, lat="latitude", lon="longitude", zoom=3, height=300) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) # 生成HTML文件并自动打开浏览器 fig.write_html("interactive_map.html", auto_open=True)
关闭浏览器后无任何遗留进程,同时保留地图的交互性。
2. 手动控制服务器进程(支持Ctrl+C终止)
如果仍需使用fig.show()的临时服务模式,可手动捕获服务器实例并通过信号处理器确保退出时清理:
import plotly.express as px import signal import sys def cleanup_server(server): # 终止后台HTTP服务器 server.stop() sys.exit(0) fig = px.scatter_mapbox(post_df, lat="latitude", lon="longitude", zoom=3, height=300) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) # 获取show()返回的服务器对象 server = fig.show(renderer="browser") # 注册Ctrl+C信号处理器,触发时清理服务器 signal.signal(signal.SIGINT, lambda sig, frame: cleanup_server(server)) # 阻塞主进程,直到收到终止信号 signal.pause()
此时主进程会保持运行,按下Ctrl+C时会主动终止后台服务器进程,主进程也会正常退出,无残留。
3. 切换静态渲染器(牺牲交互性)
如果不需要地图交互性,可改用静态渲染器(如SVG),无需启动后台服务:
import plotly.express as px import plotly.io as pio # 设置默认渲染器为SVG pio.renderers.default = "svg" fig = px.scatter_mapbox(post_df, lat="latitude", lon="longitude", zoom=3, height=300) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.show()
此方法会直接在终端或默认图像查看器中显示静态图,无进程残留,但失去了地图缩放、点击等交互功能。
内容的提问来源于stack exchange,提问作者user3310334
相关产品推荐
相关产品推荐

