예제 #1
0
파일: PyBerry.py 프로젝트: arjanraj/pyberry
def edit_book():
    to_do = input(
        "We're going to edit a book.  Do you have the barcode? [y/N]: ")
    if to_do.strip() == "" or to_do.strip().lower() == "n":
        results = search()
        i = 1
        for item in results:
            print(
                (str(i) + ") " +
                 str(item)))  # not sure how this will come out, same as above.
        edit_choice = input("Which one is it? ")

        edit_choice = int(edit_choice)
        edit_choice = results[edit_choice - 1]
        edit_choice = list(edit_choice)
        edit_choice = create_book_from_list(edit_choice)
        edit(edit_choice)

    elif to_do.strip().lower() == "y":
        edit_choice = input("Ok, enter it now: ")
        if edit_choice.strip() == "":
            print("Invalid input.")
        else:
            edit_choice = int(edit_choice)
            the_db = Bdb(dbLocation)
            edit_choice = the_db.retrieve(edit_choice)
            edit_choice = create_book_from_list(
                edit_choice)  # might not need this?
            edit(edit_choice)
예제 #2
0
파일: PyBerry.py 프로젝트: arjanraj/pyberry
def search():
    """
    Do searching and user-interaction for it.

    @return: a list of search results
    """

    print("Welcome to searching!")
    print(
        '''You can search by: title, authors, barcode, isbn, number of pages, publication year,
    location, description, call number, or tags.''')
    search_field = input("Which would you like to search by? ")
    search_term = input("OK, go ahead: ")

    if '' == search_field or '' == search_term:
        return 2

    if search_field not in terms:
        print("Error, exiting.")
        return
    elif search_term == "":
        print("Error, exiting.")
        return
    else:
        if search_field in substitutions:
            search_field = substitutions[search_field]
        the_db = Bdb(dbLocation)
        return the_db.search(search_field, search_term)
예제 #3
0
def edit_book():
    to_do = input("We're going to edit a book.  Do you have the barcode? [y/N]: ")
    if to_do.strip() == "" or to_do.strip().lower() == "n":
        results = search()
        i = 1
        for item in results:
            print((str(i) + ") " + str(item)))  # not sure how this will come out, same as above.
        edit_choice = input("Which one is it? ")

        edit_choice = int(edit_choice)
        edit_choice = results[edit_choice - 1]
        edit_choice = list(edit_choice)
        edit_choice = create_book_from_list(edit_choice)
        edit(edit_choice)

    elif to_do.strip().lower() == "y":
        edit_choice = input("Ok, enter it now: ")
        if edit_choice.strip() == "":
            print("Invalid input.")
        else:
            edit_choice = int(edit_choice)
            the_db = Bdb(dbLocation)
            edit_choice = the_db.retrieve(edit_choice)
            edit_choice = create_book_from_list(edit_choice)  # might not need this?
            edit(edit_choice)
 def __init__(self, project_mark,preload_dt_info={}, skip=None,skip_classes=(),delay=5):
     """ skip_classes is tuple of class objects instances of which will be ignored during analysis"""
     Bdb.__init__(self, skip=skip)
     self._project_mark = project_mark
     self._used_classes_dict = preload_dt_info
     self._skip_classes = skip_classes
     self._delay = delay
예제 #5
0
def search():
    """
    Do searching and user-interaction for it.

    @return: a list of search results
    """

    print("Welcome to searching!")
    print('''You can search by: title, authors, barcode, isbn, number of pages, publication year,
    location, description, call number, or tags.''')
    search_field = input("Which would you like to search by? ")
    search_term = input("OK, go ahead: ")

    if '' == search_field or '' == search_term:
        return 2

    if search_field not in terms:
        print("Error, exiting.")
        return
    elif search_term == "":
        print("Error, exiting.")
        return
    else:
        if search_field in substitutions:
            search_field = substitutions[search_field]
        the_db = Bdb(dbLocation)
        return the_db.search(search_field, search_term)
예제 #6
0
파일: __init__.py 프로젝트: Simplistix/zdb
 def __init__(self):
     Bdb.__init__(self)
     Cmd.__init__(self)
     self.rcLines = []
     self.prompt = '(zdb) '
     self.aliases = {}
     self.mainpyfile = ''
     self._wait_for_mainpyfile = 0
     self.commands_defining = None
예제 #7
0
파일: __init__.py 프로젝트: tuxcanfly/w
 def __init__(self, app, skip=None):
     Bdb.__init__(self, skip=skip)
     self.begun = False
     self.app = app
     self.ws = WebSocket('localhost', randint(10000, 60000))
     self.connected = False
     tries = 1
     while self.ws == 'FAIL' and tries < 10:
         tries += 1
         self.ws = WebSocket('localhost', randint(10000, 60000))
예제 #8
0
    def user_line(self, frame):
        if 'bdb.py' in frame.f_code.co_filename:
            # roflcopter, major hack
            return

        Bdb.user_line(self, frame)

        # this sets the frame, and then blocks until the web frontend has
        # signalled that it's ok to continue
        fud.tornado_server.current_frame.set_frame(frame)
예제 #9
0
    def __init__(self, action_handler, **kwargs):
        super(ManagedDebugger, self).__init__(**kwargs)
        self._bdb = Bdb()
        self._sandbox = Sandbox()
        self._handler = action_handler

        self._bdb.user_call = self._bdb_call
        self._bdb.user_line = self._bdb_line
        self._bdb.user_return = self._bdb_return
        self._bdb.user_exception = self._bdb_exception
예제 #10
0
파일: debugger.py 프로젝트: eklitzke/fud
    def user_line(self, frame):
        if 'bdb.py' in frame.f_code.co_filename:
            # roflcopter, major hack
            return

        Bdb.user_line(self, frame)
        
        # this sets the frame, and then blocks until the web frontend has
        # signalled that it's ok to continue
        fud.tornado_server.current_frame.set_frame(frame)
    def __init__(self, socket):
        Bdb.__init__(self)
        self.socket = socket

        # Imports (attach to this class, don't pollute __main__)
        import json
        self.json = json

        # Remember input pipe attributes
        self._input_buffer = ''
예제 #12
0
    def __init__(self):
        Bdb.__init__(self)

        self.mainpyfile = ''
        self.filter_var_dict_wait_for_mainpyfile = 0

        # each entry contains a dict with the information for a single
        # executed line
        self.trace = []

        self._exception = None
예제 #13
0
    def __init__(self):
        Bdb.__init__(self)

        self.mainpyfile = ''
        self.filter_var_dict_wait_for_mainpyfile = 0

        # each entry contains a dict with the information for a single
        # executed line
        self.trace = []

        self._exception = None
예제 #14
0
파일: frosch.py 프로젝트: gvx/frosch
def retrieve_post_mortem_stack_infos(traceback_):
    """Retrieve post mortem all local and global
    variables of given traceback"""

    base_debugger = Bdb()
    stack, i = base_debugger.get_stack(None, traceback_)

    # Get global and local vals
    locals_ = stack[i][0].f_locals
    globals_ = stack[i][0].f_globals
    return locals_, globals_
예제 #15
0
파일: __init__.py 프로젝트: fdev31/wdb
 def __init__(self, app, skip=None):
     try:
         Bdb.__init__(self, skip=skip)
     except TypeError:
         Bdb.__init__(self)
     self.begun = False
     self.app = app
     self.ws = WebSocket('0.0.0.0', randint(10000, 60000))
     self.connected = False
     tries = 1
     while self.ws == 'FAIL' and tries < 10:
         tries += 1
         self.ws = WebSocket('0.0.0.0', randint(10000, 60000))
예제 #16
0
파일: PyBerry.py 프로젝트: arjanraj/pyberry
def delete_book():
    to_do = input(
        '''We're going to delete a book.  Do you have the barcode? [y/N]: ''')
    if to_do.strip() == "" or to_do.strip().lower() == "n":
        results = search()
        i = 1
        for item in results:
            print((i + ") " + item))  # not sure how this will come out.
        del_me = input("Which one is it? ")

        del_me = int(del_me)

        del_me = results[del_me - 1]
        del_me = del_me.split(",")
        del_me = Book(
            del_me[0])  # this is really fudged atm.  serious testing needed
        the_db = Bdb(dbLocation)
        the_db.delete(del_me)
        print("Deleted.")

    elif to_do.strip().lower() == "y":
        del_me = input("Ok, enter it now: ")
        if del_me.strip() == "":
            print("Invalid input.")
        else:
            del_me = int(del_me)
            del_me = Book(del_me)
            the_db = Bdb(dbLocation)
            the_db.delete(del_me)
            print("Deleted.")
예제 #17
0
파일: __init__.py 프로젝트: chiehwen/wdb
 def __init__(self, port, skip=None):
     MetaWdbRequest._last_inst = self
     try:
         Bdb.__init__(self, skip=skip)
     except TypeError:
         Bdb.__init__(self)
     self.begun = False
     self.connected = False
     self.make_web_socket(port)
     breaks_per_file_lno = Breakpoint.bplist.values()
     for bps in breaks_per_file_lno:
         breaks = list(bps)
         for bp in breaks:
             args = bp.file, bp.line, bp.temporary, bp.cond
             self.set_break(*args)
             log.info('Resetting break %s' % repr(args))
예제 #18
0
 def from_frame(cls, frame, debugger: bdb.Bdb):
     code = frame.f_code
     return cls(
         funcname=code.co_name,
         filename=debugger.canonic(code.co_filename),
         linenum=frame.f_lineno,
     )
예제 #19
0
def edit(edit_book):
    print('''I'm going to show you each element of the book.  If you don't want
              to change it, just press enter.  Otherwise, enter a new value.
              For multiple authors and tags, separate them by a comma.
              e.g. author1,author2,author3''')
    new_book = {}
    new_book['barcode'] = input("Barcode: " + str(edit_book.bc))
    new_book['isbn'] = input("ISBN: " + str(edit_book.isbn))
    new_book['title'] = input("Title: " + str(edit_book.title))  # doesn't pull info for anything below.
    new_book['authors'] = input("Authors: " + str(edit_book.authors))
    new_book['pages'] = input("Number of Pages: " + str(edit_book.pages))
    new_book['publ_year'] = input("Publication Year: " + str(edit_book.publ_year))
    new_book['publisher'] = input("Publisher: " + str(edit_book.publisher))
    new_book['location'] = input("Location: " + str(edit_book.location))
    new_book['description'] = input("Description: " + str(edit_book.description))
    new_book['call_num'] = input("Call number: " + str(edit_book.call_num))
    new_book['tags'] = input("Tags: " + str(edit_book.tags))

    for key, value in new_book.items():
        if value == '':
            new_book[key] = None

    old_bc = edit_book.bc # we need this to ensure we don't create a duplicate db entry
    edit_book.edit(new_book['barcode'], new_book['isbn'], new_book['title'], new_book['authors'],
                   new_book['pages'], new_book['publ_year'], new_book['publisher'],
                   new_book['location'], new_book['description'], new_book['call_num'],
                   new_book['tags'])
    the_db = Bdb(dbLocation)
    if edit_book.bc is None:
        the_db.store(edit_book)
    else:
        the_db.delete(Book(old_bc))
        the_db.store(edit_book)
    print("Success!")
예제 #20
0
    def __init__(self):
        Bdb.__init__(self)
        self.fncache = {}
        self.botframe = None

        self.__queue = Queue.Queue(0)

        # self._lock governs which thread the debugger will stop in.
        self._lock = ThreadChoiceLock()

        self.repr = repr = Repr()
        repr.maxstring = 100
        repr.maxother = 100
        self.maxdict2 = 1000

        self._running = 0
        self.cleanupServer()
        self.stopframe = ()  # Don't stop unless requested to do so.
예제 #21
0
    def __init__(self):
        Bdb.__init__(self)
        self.fncache = {}
        self.botframe = None

        self.__queue = Queue.Queue(0)

        # self._lock governs which thread the debugger will stop in.
        self._lock = ThreadChoiceLock()

        self.repr = repr = Repr()
        repr.maxstring = 100
        repr.maxother = 100
        self.maxdict2 = 1000

        self._running = 0
        self.cleanupServer()
        self.stopframe = ()  # Don't stop unless requested to do so.
예제 #22
0
파일: debugger.py 프로젝트: uadnan/PyTrace
    def __init__(self, action_handler, **kwargs):
        super(ManagedDebugger, self).__init__(**kwargs)
        self._bdb = Bdb()
        self._sandbox = Sandbox()
        self._handler = action_handler

        self._bdb.user_call = self._bdb_call
        self._bdb.user_line = self._bdb_line
        self._bdb.user_return = self._bdb_return
        self._bdb.user_exception = self._bdb_exception
예제 #23
0
    def from_frame(cls, frame, debugger: bdb.Bdb):
        code = frame.f_code

        # Uncomment to see the bytecode
        # b = dis.Bytecode(frame.f_code, current_offset=frame.f_lasti)
        # print(b.dis(), file=sys.__stderr__)

        return cls(
            filename=debugger.canonic(code.co_filename),
            linenum=frame.f_lineno,
            inst_index=frame.f_lasti,
        )
예제 #24
0
 def run(self, cmd, globals=None, locals=None):
     try:
         self._running = 1
         try:
             Bdb.run(self, cmd, globals, locals)
         except (BdbQuit, SystemExit):
             pass
         except:
             import traceback
             traceback.print_exc()
             if self._lock.acquire(0):
                 # Provide post-mortem analysis.
                 self.exc_info = sys.exc_info()
                 self.frame = self.exc_info[2].tb_frame
                 self.quitting = 0
                 self.eventLoop()
     finally:
         sys.settrace(None)  # Just to be sure
         self.quitting = 1
         self._running = 0
         self.cleanupServer()
예제 #25
0
 def run(self, cmd, globals=None, locals=None):
     try:
         self._running = 1
         try:
             Bdb.run(self, cmd, globals, locals)
         except (BdbQuit, SystemExit):
             pass
         except:
             import traceback
             traceback.print_exc()
             if self._lock.acquire(0):
                 # Provide post-mortem analysis.
                 self.exc_info = sys.exc_info()
                 self.frame = self.exc_info[2].tb_frame
                 self.quitting = 0
                 self.eventLoop()
     finally:
         sys.settrace(None)  # Just to be sure
         self.quitting = 1
         self._running = 0
         self.cleanupServer()
예제 #26
0
def delete_book():
    to_do = input('''We're going to delete a book.  Do you have the barcode? [y/N]: ''')
    if to_do.strip() == "" or to_do.strip().lower() == "n":
        results = search()
        i = 1
        for item in results:
            print((i + ") " + item))  # not sure how this will come out.
        del_me = input("Which one is it? ")

        del_me = int(del_me)

        del_me = results[del_me - 1]
        del_me = del_me.split(",")
        del_me = Book(del_me[0])  # this is really fudged atm.  serious testing needed
        the_db = Bdb(dbLocation)
        the_db.delete(del_me)
        print("Deleted.")

    elif to_do.strip().lower() == "y":
        del_me = input("Ok, enter it now: ")
        if del_me.strip() == "":
            print("Invalid input.")
        else:
            del_me = int(del_me)
            del_me = Book(del_me)
            the_db = Bdb(dbLocation)
            the_db.delete(del_me)
            print("Deleted.")
예제 #27
0
파일: PyBerry.py 프로젝트: arjanraj/pyberry
def edit(edit_book):
    print('''I'm going to show you each element of the book.  If you don't want
              to change it, just press enter.  Otherwise, enter a new value.
              For multiple authors and tags, separate them by a comma.
              e.g. author1,author2,author3''')
    new_book = {}
    new_book['barcode'] = input("Barcode: " + str(edit_book.bc))
    new_book['isbn'] = input("ISBN: " + str(edit_book.isbn))
    new_book['title'] = input(
        "Title: " +
        str(edit_book.title))  # doesn't pull info for anything below.
    new_book['authors'] = input("Authors: " + str(edit_book.authors))
    new_book['pages'] = input("Number of Pages: " + str(edit_book.pages))
    new_book['publ_year'] = input("Publication Year: " +
                                  str(edit_book.publ_year))
    new_book['publisher'] = input("Publisher: " + str(edit_book.publisher))
    new_book['location'] = input("Location: " + str(edit_book.location))
    new_book['description'] = input("Description: " +
                                    str(edit_book.description))
    new_book['call_num'] = input("Call number: " + str(edit_book.call_num))
    new_book['tags'] = input("Tags: " + str(edit_book.tags))

    for key, value in new_book.items():
        if value == '':
            new_book[key] = None

    old_bc = edit_book.bc  # we need this to ensure we don't create a duplicate db entry
    edit_book.edit(new_book['barcode'], new_book['isbn'], new_book['title'],
                   new_book['authors'], new_book['pages'],
                   new_book['publ_year'], new_book['publisher'],
                   new_book['location'], new_book['description'],
                   new_book['call_num'], new_book['tags'])
    the_db = Bdb(dbLocation)
    if edit_book.bc is None:
        the_db.store(edit_book)
    else:
        the_db.delete(Book(old_bc))
        the_db.store(edit_book)
    print("Success!")
예제 #28
0
def add_book():
    add_option = input('''Let's add a book.  How would you like to add it?\n
                              1) Manually\n
                              2) Search by ISBN\n
                              3) Search by Title: ''')

    add_option = int(add_option)

    if add_option == 1:
        manual_add = {}
        print("If you have multiple authors or tags, please separate them with a comma.")
        print("e.g. author1,author2,author3")
        print("To autogenerate a barcode, enter -1 for it.")
        print()
        for item in terms:
            manual_add[item] = input("Please enter the " + item + ": ")

        for item in manual_add:
            if item in substitutions:
                manual_add[substitutions[item]] = manual_add.pop(item)

        manual_book = create_book_from_dict(manual_add)
        book_db = Bdb(dbLocation)
        book_db.store(manual_book)

    elif add_option == 2:
        isbn = input("Please enter the 10 or 13 digit ISBN: ")
        lookup = Lookup()
        book = lookup.by_isbn(isbn)
        bc = input('''Please enter a unique barcode, or -1 to autogenerate: ''')

        bc = int(bc)

        book.bc = bc

        location = input('''Please enter the location of the book, default blank: ''')
        book.location = location

        call_num = input('''Please enter the call number of the book: ''')
        book.call_num = call_num

        tags = input('''Please enter any tags, separated by a comma: ''')
        tags = tags.strip()
        book.tags = tags

        print('''Ok, everything should be set.  I'll show you what I've got,
        and if it looks good, just press enter, otherwise type something in
        and I'll return you to the beginning.''')

        book.print_check()

        is_ok = input("")

        if is_ok != "":  # not 100% sure this will work
            raise ValueError
        else:
            book_db = Bdb(dbLocation)
            book_db.store(book)

    elif add_option == 3:
        title = input("Please enter the title you'd like to search for:")
        lookup = Lookup()
        input("The following are the results.  Please enter the number of the " +
                  "result you'd like.  Press any key to display them.")
        books = []
        for index, book in enumerate(lookup.by_title(title), start=1):
            if index == 11:
                break  # only print first 10 results?? Not very elegant.
            print('%i) Title: %s, Author(s): %s' % (
                index,
                book.title,
                str(book.authors).strip('[]')
            ))
            books.append(book)
        user_choice = input("Which result would you like? Or hit enter for none.")

        if user_choice == '':
            return 2

        user_choice = int(user_choice)

        user_choice -= 1  # need to compensate for off-by-one.

        book = books[user_choice]

        bc = input('''Please enter a unique barcode, or -1 to autogenerate: ''')
        bc = int(bc)
        book.bc = bc

        location = input('''Please enter the location of the book, default blank: ''')
        book.location = location

        call_num = input('''Please enter the call number of the book: ''')
        book.call_num = call_num

        tags = input('''Please enter any tags, separated by a comma: ''')
        tags = tags.strip()
        book.tags = tags

        assert isinstance(book, Book)
        print('''Ok, everything should be set.  I'll show you what I've got,
        and if it looks good, just press enter, otherwise type something in
        and I'll return you to the beginning.''')

        book.print_check()

        is_ok = input("")

        if is_ok != "":
            raise ValueError  # should consider changing to a UserQuit exception.
        else:
            book_db = Bdb(dbLocation)
            book_db.store(book)
예제 #29
0
 def run(self, script):
     Bdb.run(self, script, self.globals, self.locals)
예제 #30
0
 def __init__(self, *args):
     Bdb.__init__(self, *args)
     self.codes = set()
예제 #31
0
 def __init__(self, panel, *args, **kargs):
     Bdb.__init__(self, *args, **kargs)
     self.panel = panel
예제 #32
0
 def __init__(self, *args):
     Bdb.__init__(self, *args)
     self.stack = []
     self.current_module = None
예제 #33
0
 def __init__(self, panel, *args, **kargs):
     Bdb.__init__(self, *args, **kargs)
     self.panel = panel
예제 #34
0
 def __init__(self, *args, entry_func, module, stopping_conditions,
              memoization_mapping):
     Bdb.__init__(self, *args)
     pass
예제 #35
0
 def reset(self):
     Bdb.reset(self)
     self.forget()
예제 #36
0
파일: debugger.py 프로젝트: eklitzke/fud
 def set_trace(self, frame=None):
     Bdb.set_trace(self, frame)
예제 #37
0
 def reset(self):
     Bdb.reset(self)
     self.forget()
예제 #38
0
def show_all_books():
    the_db = Bdb(dbLocation)
    for item in the_db.get_all():
        print(item)
    input("Press any key to continue.")
예제 #39
0
 def run(self, *args, **kargs):
     Bdb.run(self, *args, **kargs)
예제 #40
0
파일: PyBerry.py 프로젝트: arjanraj/pyberry
def show_all_books():
    the_db = Bdb(dbLocation)
    for item in the_db.get_all():
        print(item)
    input("Press any key to continue.")
예제 #41
0
 def __init__(self, *args):
     Bdb.__init__(self, *args)
     self.codes = set()
예제 #42
0
파일: debugger.py 프로젝트: uadnan/PyTrace
class ManagedDebugger(object):
    """ Managed Python Debugger """

    _wait_stack_height = 0
    _done = False
    _excep_logged = False
    _script_lines = []

    def __init__(self, action_handler, **kwargs):
        super(ManagedDebugger, self).__init__(**kwargs)
        self._bdb = Bdb()
        self._sandbox = Sandbox()
        self._handler = action_handler

        self._bdb.user_call = self._bdb_call
        self._bdb.user_line = self._bdb_line
        self._bdb.user_return = self._bdb_return
        self._bdb.user_exception = self._bdb_exception

    def _initialize(self):
        self._done = False
        self._excep_logged = False

        self._wait_stack_height = 0

    # bdb Callbacks
    def _bdb_call(self, frame, args):
        if self._done:
            return  # Execution is stopped

        if frame.f_code.co_filename != "<string>" or frame.f_lineno <= 0:
            self._wait_stack_height += 1
            return

        if self._wait_stack_height:
            self._wait_stack_height += 1
            return

        if not self._bdb.stop_here(frame):
            return

        script_line = self._get_script_line(frame.f_code.co_firstlineno)
        if contains_class_defination(script_line):
            self._wait_stack_height = 1
            return

        args = self._extract_passed_arguments(frame)
        self.trigger(DebuggerEvent.EnterBlock, frame=frame, arguments=args)

    def _extract_passed_arguments(self, frame):
        function = frame.f_globals[frame.f_code.co_name]
        arg_specs = inspect.getargspec(function)

        args = {
            arg: frame.f_locals[arg]
            for arg in arg_specs.args
        }

        if arg_specs.varargs:
            args[arg_specs.varargs] = frame.f_locals[arg_specs.varargs]

        if arg_specs.keywords:
            args[arg_specs.keywords] = frame.f_locals[arg_specs.keywords]

        return args

    def _bdb_line(self, frame):
        if self._done or self._wait_stack_height:
            return

        self._excep_logged = False
        self.trigger(DebuggerEvent.StepLine, frame=frame)

    def _bdb_return(self, frame, value):
        if self._done:
            return

        if self._wait_stack_height:
            self._wait_stack_height -= 1
        elif frame.f_code.co_filename == "<string>":
            self.trigger(DebuggerEvent.ExitBlock, frame=frame, return_value=value)

    def _bdb_exception(self, frame, info):
        if self._done or self._wait_stack_height:
            return

        self._excep_logged = True
        ex_type, value, tb = info

        self.trigger(DebuggerEvent.Exception, frame=frame, ex_type=ex_type,
                     value=value, traceback=tb)

    def trigger(self, event, *args, **kwargs):
        return self._handler(event, *args, **kwargs)

    def _get_script_line(self, n):
        return self.script_lines[n - 1]

    def get_stack(self, frame, tb):
        return self._bdb.get_stack(frame, tb)

    @property
    def stdout(self):
        return self._sandbox.stdout

    def run(self, script, input_queue=None):
        self._initialize()

        try:
            self.script_lines = script.splitlines()
            self._sandbox.run(script, input_queue, runner=self._bdb.run)
        except SyntaxError as ex:
            self.trigger(DebuggerEvent.SyntaxError, exception=ex)
        except:
            if not self._excep_logged:
                logger.exception(
                    "Internal Error in Debugger\n"
                    "Script:\n%s\n"
                    "Input Queue:%s",
                    script, input_queue
                )
                ex_type, value, tb = sys.exc_info()
                self.trigger(DebuggerEvent.SystemError, type=ex_type,
                             value=value, traceback=tb)
        finally:
            self._done = True
예제 #43
0
 def set_trace(self, frame=None):
     Bdb.set_trace(self, frame)
예제 #44
0
class ManagedDebugger(object):
    """ Managed Python Debugger """

    _wait_stack_height = 0
    _done = False
    _excep_logged = False
    _script_lines = []

    def __init__(self, action_handler, **kwargs):
        super(ManagedDebugger, self).__init__(**kwargs)
        self._bdb = Bdb()
        self._sandbox = Sandbox()
        self._handler = action_handler

        self._bdb.user_call = self._bdb_call
        self._bdb.user_line = self._bdb_line
        self._bdb.user_return = self._bdb_return
        self._bdb.user_exception = self._bdb_exception

    def _initialize(self):
        self._done = False
        self._excep_logged = False

        self._wait_stack_height = 0

    # bdb Callbacks
    def _bdb_call(self, frame, args):
        if self._done:
            return  # Execution is stopped

        if frame.f_code.co_filename != "<string>" or frame.f_lineno <= 0:
            self._wait_stack_height += 1
            return

        if self._wait_stack_height:
            self._wait_stack_height += 1
            return

        if not self._bdb.stop_here(frame):
            return

        script_line = self._get_script_line(frame.f_code.co_firstlineno)
        if contains_class_defination(script_line):
            self._wait_stack_height = 1
            return

        args = self._extract_passed_arguments(frame)
        self.trigger(DebuggerEvent.EnterBlock, frame=frame, arguments=args)

    def _extract_passed_arguments(self, frame):
        function = frame.f_globals[frame.f_code.co_name]
        arg_specs = inspect.getargspec(function)

        args = {arg: frame.f_locals[arg] for arg in arg_specs.args}

        if arg_specs.varargs:
            args[arg_specs.varargs] = frame.f_locals[arg_specs.varargs]

        if arg_specs.keywords:
            args[arg_specs.keywords] = frame.f_locals[arg_specs.keywords]

        return args

    def _bdb_line(self, frame):
        if self._done or self._wait_stack_height:
            return

        self._excep_logged = False
        self.trigger(DebuggerEvent.StepLine, frame=frame)

    def _bdb_return(self, frame, value):
        if self._done:
            return

        if self._wait_stack_height:
            self._wait_stack_height -= 1
        elif frame.f_code.co_filename == "<string>":
            self.trigger(DebuggerEvent.ExitBlock,
                         frame=frame,
                         return_value=value)

    def _bdb_exception(self, frame, info):
        if self._done or self._wait_stack_height:
            return

        self._excep_logged = True
        ex_type, value, tb = info

        self.trigger(DebuggerEvent.Exception,
                     frame=frame,
                     ex_type=ex_type,
                     value=value,
                     traceback=tb)

    def trigger(self, event, *args, **kwargs):
        return self._handler(event, *args, **kwargs)

    def _get_script_line(self, n):
        return self.script_lines[n - 1]

    def get_stack(self, frame, tb):
        return self._bdb.get_stack(frame, tb)

    @property
    def stdout(self):
        return self._sandbox.stdout

    def run(self, script, input_queue=None):
        self._initialize()

        try:
            self.script_lines = script.splitlines()
            self._sandbox.run(script, input_queue, runner=self._bdb.run)
        except SyntaxError as ex:
            self.trigger(DebuggerEvent.SyntaxError, exception=ex)
        except:
            if not self._excep_logged:
                logger.exception(
                    "Internal Error in Debugger\n"
                    "Script:\n%s\n"
                    "Input Queue:%s", script, input_queue)
                ex_type, value, tb = sys.exc_info()
                self.trigger(DebuggerEvent.SystemError,
                             type=ex_type,
                             value=value,
                             traceback=tb)
        finally:
            self._done = True
예제 #45
0
 def run(self, *args, **kargs):
     Bdb.run(self, *args, **kargs)
예제 #46
0
 def __init__(self, *args):
     Bdb.__init__(self, *args)
     self.stack = set()
예제 #47
0
 def __init__(self):
     Bdb.__init__(self)
     self.line_handler = None
     self.last_lineno = None
     self.globals = {}
     self.locals = self.globals
 def __init__(self):
     Bdb.__init__(self)
     self.breakpoints = dict()
     self.set_trace()
예제 #49
0
파일: PyBerry.py 프로젝트: arjanraj/pyberry
def add_book():
    add_option = input('''Let's add a book.  How would you like to add it?\n
                              1) Manually\n
                              2) Search by ISBN\n
                              3) Search by Title: ''')

    add_option = int(add_option)

    if add_option == 1:
        manual_add = {}
        print(
            "If you have multiple authors or tags, please separate them with a comma."
        )
        print("e.g. author1,author2,author3")
        print("To autogenerate a barcode, enter -1 for it.")
        print()
        for item in terms:
            manual_add[item] = input("Please enter the " + item + ": ")

        for item in manual_add:
            if item in substitutions:
                manual_add[substitutions[item]] = manual_add.pop(item)

        manual_book = create_book_from_dict(manual_add)
        book_db = Bdb(dbLocation)
        book_db.store(manual_book)

    elif add_option == 2:
        isbn = input("Please enter the 10 or 13 digit ISBN: ")
        lookup = Lookup()
        book = lookup.by_isbn(isbn)
        bc = input(
            '''Please enter a unique barcode, or -1 to autogenerate: ''')

        bc = int(bc)

        book.bc = bc

        location = input(
            '''Please enter the location of the book, default blank: ''')
        book.location = location

        call_num = input('''Please enter the call number of the book: ''')
        book.call_num = call_num

        tags = input('''Please enter any tags, separated by a comma: ''')
        tags = tags.strip()
        book.tags = tags

        print('''Ok, everything should be set.  I'll show you what I've got,
        and if it looks good, just press enter, otherwise type something in
        and I'll return you to the beginning.''')

        book.print_check()

        is_ok = input("")

        if is_ok != "":  # not 100% sure this will work
            raise ValueError
        else:
            book_db = Bdb(dbLocation)
            book_db.store(book)

    elif add_option == 3:
        title = input("Please enter the title you'd like to search for:")
        lookup = Lookup()
        input(
            "The following are the results.  Please enter the number of the " +
            "result you'd like.  Press any key to display them.")
        books = []
        for index, book in enumerate(lookup.by_title(title), start=1):
            if index == 11:
                break  # only print first 10 results?? Not very elegant.
            print('%i) Title: %s, Author(s): %s' %
                  (index, book.title, str(book.authors).strip('[]')))
            books.append(book)
        user_choice = input(
            "Which result would you like? Or hit enter for none.")

        if user_choice == '':
            return 2

        user_choice = int(user_choice)

        user_choice -= 1  # need to compensate for off-by-one.

        book = books[user_choice]

        bc = input(
            '''Please enter a unique barcode, or -1 to autogenerate: ''')
        bc = int(bc)
        book.bc = bc

        location = input(
            '''Please enter the location of the book, default blank: ''')
        book.location = location

        call_num = input('''Please enter the call number of the book: ''')
        book.call_num = call_num

        tags = input('''Please enter any tags, separated by a comma: ''')
        tags = tags.strip()
        book.tags = tags

        assert isinstance(book, Book)
        print('''Ok, everything should be set.  I'll show you what I've got,
        and if it looks good, just press enter, otherwise type something in
        and I'll return you to the beginning.''')

        book.print_check()

        is_ok = input("")

        if is_ok != "":
            raise ValueError  # should consider changing to a UserQuit exception.
        else:
            book_db = Bdb(dbLocation)
            book_db.store(book)