Skip to main content
 首页 » 编程设计

python之我应该如何解决 Python2.6 下的 Plotly 语法错误

2025年04月02日15zhwl

我被迫将 Python2.6 用于 CGI 项目,并尝试使用 Plotly 创建直方图。

这是创建直方图的函数:

def get_histogram(self, dataset_uuid, target, title, xaxisTitle, yaxisTitle): 
    max_threshold = self.get_max_threshold(dataset_uuid, target) 
 
    thresholds = [0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5] 
    counts = [] 
 
    for i, percentage in enumerate(thresholds): 
 
        # Query the database for all of the records with frequencies above the 
        # threshold. 
        result = (self.session.query(Mesh) 
            .filter(Mesh.frequency >= percentage * max_threshold) 
        ) 
 
        # Appends the fetched record count to the list of counts 
        counts.append(result.count()) 
 
        # Change percentages from float to integer 
        thresholds[i] = percentage * 100 
 
    graph = go.Histogram( 
        x = thresholds, 
        y = counts, 
        type='bar' 
    ) 
 
    layout = go.Layout( 
        title = title, 
        xaxis = dict( 
            title = xaxisTitle 
        ), 
        yaxis = dict( 
            title = yaxisTitle 
        ) 
    ) 
 
    data = [graph] 
    figure = go.Figure(data = data, layout = layout) 
 
    return json.dumps(figure, cls=plotly.utils.PlotlyJSONEncoder) 

在 Python2.7 下,我的脚本按预期运行,但是,当我尝试 2.6 时,我收到以下语法错误:

Traceback (most recent call last): 
  File "index.cgi", line 4, in <module> 
    from viads import Application 
  File "/Library/WebServer/Documents/viads/viads/__init__.py", line 3, in <module> 
    from application import Application 
  File "/Library/WebServer/Documents/viads/viads/application.py", line 8, in <module> 
    from mysqlDatabase import MysqlDatabase 
  File "/Library/WebServer/Documents/viads/viads/mysqlDatabase.py", line 3, in <module> 
    from database import Database 
  File "/Library/WebServer/Documents/viads/viads/database.py", line 9, in <module> 
    import plotly.plotly 
  File "/Library/Python/2.6/site-packages/plotly/__init__.py", line 31, in <module> 
    from plotly import (plotly, graph_objs, grid_objs, tools, utils, session, 
  File "/Library/Python/2.6/site-packages/plotly/plotly/__init__.py", line 10, in <module> 
    from . plotly import ( 
  File "/Library/Python/2.6/site-packages/plotly/plotly/plotly.py", line 114 
    user_plot_options = {k: v for k, v in user_plot_options.items() 
                                ^ 
SyntaxError: invalid syntax 

调查 plotly.py 揭示了以下列表理解:

user_plot_options = {k: v for k, v in user_plot_options.items()              
                      if k in default_plot_options} 

我认为这是在尝试将 double 列表转换为 Plotly 配置选项的字典。

由于这是 Python2.6 的 Plotly 源代码本身的语法错误,我是否应该为我自己的项目修补它并考虑将其贡献回 Plotly?

附言我了解使用旧版本 Python 和不使用 FCGI 的缺点

请您参考如下方法:

我通过安装旧版本的 Plotly 解决了这个问题,特别是来自 https://github.com/plotly/plotly.py/releases 的 1.6.7 版本.