2013-05-18 3 views
-2

나는 그들을 고칠 수있는 방법을 이해하지 못하는 파이썬 오류가 몇 가지 있습니다.파이썬 오류. 게시물의 목록

감사합니다. 모든 오류의

목록 :

Traceback (most recent call last): 
    File "C:\Users\----\Desktop\wm3con-master\wm3con-master\wm3con.py", line 277, 
in <module> 
    sys.exit(main()) 
    File "C:\Users\----\Desktop\wm3con-master\wm3con-master\wm3con.py", line 274, 
in main 
    return curses.wrapper(app.run_curses_app) 
    File "C:\Python32\lib\curses\wrapper.py", line 43, in wrapper 
    return func(stdscr, *args, **kwds) 
    File "C:\Users\----\Desktop\wm3con-master\wm3con-master\wm3con.py", line 230, 
in run_curses_app 
    m.set_data(self.data) 
    File "C:\Users\----\Desktop\wm3con-master\wm3con-master\wm3con.py", line 114, 
in set_data 
    dets = data.get('detections', []) 
AttributeError: 'NoneType' object has no attribute 'get' 

편집 : 아래 평 파일의 코드 (3 2에서 변환)이 작동하지 않는 것입니다 그리고 난 데이터가 함께 너희들이 무슨 뜻인지 잘 모릅니다 없음.

이것은 f- 보안 세계지도 ASCII 버전입니다.

#!/usr/bin/env python 
''' 
F-Secure Virus World Map console edition 

See README.md for more details 

Copyright 2012-2013 Jyrki Muukkonen 

Released under the MIT license. 
See LICENSE.txt or http://www.opensource.org/licenses/mit-license.php 

ASCII map in map-world-01.txt is copyright: 
"Map 1998 Matthew Thomas. Freely usable as long as this line is included" 

''' 
import curses 
import json 
import locale 
import os 
import random 
import sys 
import time 
import urllib.request, urllib.error, urllib.parse 


STREAMS = { 
    'filetest': 'wm3stream.json', 
    'wm3': 'http://worldmap3.f-secure.com/api/stream/', 
} 

MAPS = { 
    'world': { 
     # offset (as (y, x) for curses...) 
     'corners': (1, 4, 23, 73), 
     # lat top, lon left, lat bottom, lon right 
     'coords': [90.0, -180.0, -90.0, 180.0], 
     'file': 'map-world-01.txt', 
    } 
} 


class AsciiMap(object): 
    """ 
    Helper class for handling map drawing and coordinate calculations 
    """ 
    def __init__(self, map_name='world', map_conf=None, window=None, encoding=None): 
     if map_conf is None: 
      map_conf = MAPS[map_name] 
     with open(map_conf['file'], 'rb') as mapf: 
      self.map = mapf.read() 
     self.coords = map_conf['coords'] 
     self.corners = map_conf['corners'] 
     if window is None: 
      window = curses.newwin(0, 0) 
     self.window = window 

     self.data = [] 
     self.data_timestamp = None 

     # JSON contents _should_ be UTF8 (so, python internal unicode here...) 
     if encoding is None: 
      encoding = locale.getpreferredencoding() 
     self.encoding = encoding 

     # check if we can use transparent background or not 
     if curses.can_change_color(): 
      curses.use_default_colors() 
      background = -1 
     else: 
      background = curses.COLOR_BLACK 

     tmp_colors = [ 
      ('red', curses.COLOR_RED, background), 
      ('blue', curses.COLOR_BLUE, background), 
      ('pink', curses.COLOR_MAGENTA, background) 
     ] 

     self.colors = {} 
     if curses.has_colors(): 
      for i, (name, fgcolor, bgcolor) in enumerate(tmp_colors, 1): 
       curses.init_pair(i, fgcolor, bgcolor) 
       self.colors[name] = i 

    def latlon_to_coords(self, lat, lon): 
     """ 
     Convert lat/lon coordinates to character positions. 
     Very naive version, assumes that we are drawing the whole world 
     TODO: filter out stuff that doesn't fit 
     TODO: make it possible to use "zoomed" maps 
     """ 
     width = (self.corners[3]-self.corners[1]) 
     height = (self.corners[2]-self.corners[0]) 

     # change to 0-180, 0-360 
     abs_lat = -lat+90 
     abs_lon = lon+180 
     x = (abs_lon/360.0)*width + self.corners[1] 
     y = (abs_lat/180.0)*height + self.corners[0] 
     return int(x), int(y) 

    def set_data(self, data): 
     """ 
     Set/convert internal data. 
     For now it just selects a random set to show (good enough for demo purposes) 
     TODO: could use deque to show all entries 
     """ 
     entries = [] 
     formats = [ 
      "{name}/{country} {city}", 
      "{name}/{country}", 
      "{name}", 
      "{type}", 
     ] 
     dets = data.get('detections', []) 
     for det in random.sample(dets, min(len(dets), 5)): 
      #"city": "Montoire-sur-le-loir", 
      #"country": "FR", 
      #"lat": "47.7500", 
      #"long": "0.8667", 
      #"name": "Trojan.Generic.7555308", 
      #"type": "Trojan" 
      desc = "Detection" 
      # keeping it unicode here, encode() for curses later on 
      for fmt in formats: 
       try: 
        desc = fmt.format(**det) 
        break 
       except Exception: 
        pass 
      entry = (
       float(det['lat']), 
       float(det['long']), 
       '*', 
       desc, 
       curses.A_BOLD, 
       'red', 
      ) 
      entries.append(entry) 
     self.data = entries 
     # for debugging... maybe it could be shown again now that we have the live stream support 
     #self.data_timestamp = data.get('response_generated') 

    def draw(self, target): 
     """ Draw internal data to curses window """ 
     self.window.clear() 
     self.window.addstr(0, 0, self.map) 
     debugdata = [ 
      (60.16, 24.94, '*', self.data_timestamp, curses.A_BOLD, 'blue'), # Helsinki 
      #(90, -180, '1', 'top left', curses.A_BOLD, 'blue'), 
      #(-90, -180, '2', 'bottom left', curses.A_BOLD, 'blue'), 
      #(90, 180, '3', 'top right', curses.A_BOLD, 'blue'), 
      #(-90, 180, '4', 'bottom right', curses.A_BOLD, 'blue'), 
     ] 
     # FIXME: position to be defined in map config? 
     row = self.corners[2]-6 
     items_to_show = 5 
     for lat, lon, char, desc, attrs, color in debugdata + self.data: 
      # to make this work almost everywhere. see http://docs.python.org/2/library/curses.html 
      if desc: 
       desc = desc.encode(self.encoding, 'ignore') 
      if items_to_show <= 0: 
       break 
      char_x, char_y = self.latlon_to_coords(lat, lon) 
      if self.colors and color: 
       attrs |= curses.color_pair(self.colors[color]) 
      self.window.addstr(char_y, char_x, char, attrs) 
      if desc: 
       det_show = "%s %s" % (char, desc) 
      else: 
       det_show = None 

      if det_show is not None: 
       try: 
        self.window.addstr(row, 1, det_show, attrs) 
        row += 1 
        items_to_show -= 1 
       except Exception: 
        # FIXME: check window size before addstr() 
        break 
     self.window.overwrite(target) 
     self.window.leaveok(1) 


class MapApp(object): 
    """ Virus World Map ncurses application """ 
    def __init__(self, conf=None): 
     conf = dict(conf or []) 

     # stream url can be a known name, filename or url 
     stream_url = conf.get('stream_url', 'wm3') 
     stream_url = STREAMS.get(stream_url, stream_url) 
     if '://' not in stream_url and os.path.isfile(stream_url): 
      stream_url = 'file://' + os.path.abspath(stream_url) 
     self.stream_url = stream_url 

     #self.replay = True 
     self.data = None 
     self.last_fetch = 0 
     self.sleep = 10 # tenths of seconds, for curses.halfdelay() 

    def fetch_data(self, epoch_now, force_refresh=False): 
     """ (Re)fetch data from JSON stream """ 
     refresh = False 
     if force_refresh or self.data is None: 
      refresh = True 
     else: 
      # json data usually has: "polling_interval": 120 
      try: 
       poll_interval = int(self.data['polling_interval']) 
      except (ValueError, KeyError): 
       poll_interval = 60 
      if self.last_fetch + poll_interval <= epoch_now: 
       refresh = True 

     if refresh: 
      try: 
       self.data = json.load(urllib.request.urlopen(self.stream_url)) 
       self.last_fetch = epoch_now 
      except Exception: 
       pass 
     return refresh 

    def run_curses_app(self, scr): 
     """ Initialize and run the application """ 
     m = AsciiMap() 
     curses.halfdelay(self.sleep) 
     while True: 
      now = int(time.time()) 
      refresh = self.fetch_data(now) 
      m.set_data(self.data) 
      m.draw(scr) 
      scr.addstr(0, 1, "F-Secure Virus World Map '99", curses.A_BOLD) 
      scr.addstr(0, 40, time.strftime("%c UTC", time.gmtime(now)).rjust(37), curses.A_BOLD) 

      event = scr.getch() 
      if event == ord("q"): 
       break 

      # if in replay mode? 
      #elif event == ord('-'): 
      # self.sleep = min(self.sleep+10, 100) 
      # curses.halfdelay(self.sleep) 
      #elif event == ord('+'): 
      # self.sleep = max(self.sleep-10, 10) 
      # curses.halfdelay(self.sleep) 

      elif event == ord('r'): 
       # force refresh 
       refresh = True 
      elif event == ord('c'): 
       # enter config mode 
       pass 
      elif event == ord('h'): 
       # show help screen 
       pass 
      elif event == ord('m'): 
       # cycle maps 
       pass 

      # redraw window (to fix encoding/rendering bugs and to hide other messages to same tty) 
      # user pressed 'r' or new data was fetched 
      if refresh: 
       m.window.redrawwin() 


def main(argv=None): 
    """ Main function/entry point """ 
    if argv is None: 
     argv = sys.argv[1:] 
    conf = {} 
    if len(argv): 
     conf['stream_url'] = argv[0] 
    app = MapApp(conf) 
    return curses.wrapper(app.run_curses_app) 

if __name__ == '__main__': 
    sys.exit(main()) 
+1

는'data'는 파이썬'dict'하지만 ** 실행 ** 당신이 게시해야 코드 –

+0

A의 해당 없음해야한다 : 여기

오류가 발생할 코드의 핵심 부분이다 최소한의 예를 들어, 당신이 가지고있는 모든 것을 덤프가 아닌 – LtWorf

답변

3

dataNone이다 : 나는

아래 평 파일의 코드 3으로 버전 2에서 변환. 어떻게 얻었는지, 왜 None인지 확인해야합니다.

+0

나는 "데이터가 없다"라는 말을 모른다. 그러나이 파이썬 프로그램은 f-secure ASCII world map이다. – user2396964

0

데이터로드 절차에 실패 (예 : 예외 발생)가 발생하여 현재 코드가 무시로 설정되어 있습니다. 데이터를로드하려는 첫 번째 시도에서이 문제가 발생하면 응용 프로그램의 data 특성이 해당 초기화에서 None으로 유지됩니다. 나중에 다른 코드로 전달하려고하면 표시되는 오류가 발생합니다.

class MapApp(object): 
    def __init__(self, conf=None): 
     self.data = None # self.data is initially None 

    def fetch_data(self, epoch_now, force_refresh=False): 
     try: 
      self.data = json.load(urllib.request.urlopen(self.stream_url)) 
      self.last_fetch = epoch_now 
     except Exception: # exceptions from the json or urllib code above are ignored 
      pass 

    def run_curses_app(self, scr): 
     m = AsciiMap() 
     while True: 
      now = int(time.time()) 
      refresh = self.fetch_data(now) # this may fail silently 
      m.set_data(self.data) # but if it does (the first time) this fails noisily 
+0

오케이. 나 한테 고칠 수있어? 파이썬에 초보자가있어서 전체 스크립트를 망칠 수 있습니다. – user2396964

+0

간단한 수정 방법이 확실하지 않습니다. 디버깅을 시작할 때,'except Exception : pass' 라인을'fetch_data'에서 바꿔 대신 예외 정보를 출력하여 잘못된 것을 이해할 수 있습니다 :'Exception as e : print e' (하지만 다양한 방식으로 curses UI와 충돌 할 수 있음). 예외를 잡아 내지 않고 응용 프로그램을 충돌 시키도록 변경할 수도 있습니다 (따라서 데이터로드가 실패한 곳에서 예외 및 추적을 볼 수 있습니다). – Blckknght

+0

아무 것도 인쇄하지 않습니다. 나는 정말로 자동 고침 또는 이것에 무언가를 필요로 할 것이다. :/나는 어제부터이 문제를 이미 가지고 있었다. – user2396964