matplotlib xlim TypeError:“int”和“list”实例之间不支持“>”

2024-09-25 00:33:58 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我试图在我的计算机上运行的原始回购:https://github.com/kreamkorokke/cs244-final-project

import os
import matplotlib.pyplot as plt
import argparse
from attacker import check_attack_type

IMG_DIR = "./plots"

def read_lines(f, d):
    lines = f.readlines()[:-1]
    for line in lines:
        typ, time, num = line.split(',')
        if typ == 'seq':
            d['seq']['time'].append(float(time))
            d['seq']['num'].append(float(num))
        elif typ == 'ack':
            d['ack']['time'].append(float(time))
            d['ack']['num'].append(float(num))
        else:
            raise "Unknown type read while parsing log file: %s" % typ

def main():
    parser = argparse.ArgumentParser(description="Plot script for plotting sequence numbers.")
    parser.add_argument('--save', dest='save_imgs', action='store_true',
                        help="Set this to true to save images under specified output directory.")
    parser.add_argument('--attack', dest='attack',
                        nargs='?', const="", type=check_attack_type,
                        help="Attack name (used in plot names).")
    parser.add_argument('--output', dest='output_dir', default=IMG_DIR,
                        help="Directory to store plots.")
    args = parser.parse_args()
    save_imgs = args.save_imgs
    output_dir = args.output_dir
    attack_name = args.attack

    if save_imgs and attack_name not in ['div', 'dup', 'opt'] :
        print("Attack name needed for saving plot figures.")
        return

    normal_log = {'seq':{'time':[], 'num':[]}, 'ack':{'time':[], 'num':[]}}
    attack_log = {'seq':{'time':[], 'num':[]}, 'ack':{'time':[], 'num':[]}}
    normal_f = open('log.txt', 'r')
    attack_f = open('%s_attack_log.txt' % attack_name, 'r')
    
    read_lines(normal_f, normal_log)
    read_lines(attack_f, attack_log)
   
    if attack_name == 'div':
        attack_desc = 'ACK Division'
    elif attack_name == 'dup':
        attack_desc = 'DupACK Spoofing'
    elif attack_name == 'opt':
        attack_desc = 'Optimistic ACKing'
    else:
        raise 'Unknown attack type: %s' % attack_name
    norm_seq_time, norm_seq_num = normal_log['seq']['time'], normal_log['seq']['num']
    norm_ack_time, norm_ack_num = normal_log['ack']['time'], normal_log['ack']['num']
    atck_seq_time, atck_seq_num = attack_log['seq']['time'], attack_log['seq']['num']
    atck_ack_time, atck_ack_num = attack_log['ack']['time'], attack_log['ack']['num']
    plt.plot(norm_seq_time, norm_seq_num, 'b^', label='Regular TCP Data Segments')
    plt.plot(norm_ack_time, norm_ack_num, 'bx', label='Regular TCP ACKs')
    plt.plot(atck_seq_time, atck_seq_num, 'rs', label='%s Attack Data Segments' % attack_desc)
    plt.plot(atck_ack_time, atck_ack_num, 'r+', label='%s Attack ACKs' % attack_desc)
    plt.legend(loc='upper left')

    x = max(max(norm_seq_time, norm_ack_time),max(atck_seq_time, atck_ack_time))
    y = max(max(norm_seq_num, norm_ack_num),max(atck_seq_num, atck_ack_num))
    plt.xlim(0, x)
    plt.ylim(0,y)

    plt.xlabel('Time (s)')
    plt.ylabel('Sequence Number (Bytes)')

    if save_imgs:
        # Save images to figure/
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        plt.savefig(output_dir + "/" + attack_name)
    else:
        plt.show()
    
    normal_f.close()
    attack_f.close()


if __name__ == "__main__":
    main()

运行此命令后,我得到了此错误

Traceback (most recent call last):
  File "plot.py", line 85, in <module>
    main()
  File "plot.py", line 66, in main
    plt.xlim(0, a)
  File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 1427, in xlim
    ret = ax.set_xlim(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/axes/_base.py", line 3267, in set_xlim
    reverse = left > right
TypeError: '>' not supported between instances of 'int' and 'list'
Done! Please check ./plots for all generated plots.

我怎样才能解决这个问题?或者更好的是,如果有另一种方式来运行这个项目?我通过pip3安装matplotlib命令(与scapy相同)安装了matplotlib,现在我的主要python版本是python2,但我使用python3运行项目,问题是否与此有关?我错过了什么?还是关于迷你网本身


Tags: nameinlognormoutputtimeplotsave
2条回答

问题就在这方面

 x = max(max(norm_seq_time, norm_ack_time),max(atck_seq_time, atck_ack_time))

IIUC,您想为x分配这四个列表中的最大值。但是,当您将两个列表传递给max函数(例如max(norm_seq_time, norm_ack_time))时,它将返回它认为较大的列表,而不是考虑两个列表的最高值

相反,您可以执行以下操作:

x = max(norm_seq_time + norm_ack_time + atck_seq_time + atck_ack_time)

这将把四个列表连接成一个列表。然后,函数将返回所有函数中的最高值。您可能也希望对y的计算也这样做

如果这不是你想要的,或者如果你有任何进一步的问题,请让我们知道

在一位朋友的帮助下,我们通过将代码中的一部分更改为以下内容来解决此问题:

    max_norm_seq_time = max(norm_seq_time) if len(norm_seq_time) > 0 else 0
    max_norm_ack_time = max(norm_ack_time) if len(norm_ack_time) > 0 else 0    

    max_atck_seq_time = max(atck_seq_time) if len(atck_seq_time) > 0 else 0
    max_atck_ack_time = max(atck_ack_time) if len(atck_ack_time) > 0 else 0

    x =  max((max_norm_seq_time, max_norm_ack_time,\
                      max_atck_seq_time, max_atck_ack_time))
    plt.xlim([0,x])

    max_norm_seq_num = max(norm_seq_num) if len(norm_seq_num) > 0 else 0
    max_norm_ack_num = max(norm_ack_num) if len(norm_ack_num) > 0 else 0    

    max_atck_seq_num = max(atck_seq_num) if len(atck_seq_num) > 0 else 0
    max_atck_ack_num = max(atck_ack_num) if len(atck_ack_num) > 0 else 0
    plt.ylim([0, max((max_norm_seq_num, max_norm_ack_num,\
                      max_atck_seq_num, max_atck_ack_num))])
    ```
writing here just in case anyone else needs it. 

相关问题 更多 >