试图调试我的python代码但settrace没有执行

时间:2017-10-01 22:51:19

标签: python debugging sys

我已经在Windows上安装了python 2.7,但每当我运行我的代码时,这行不起作用,调试过程不会执行!!

sys.settrace(traceit) 

这是代码

import sys
import pyreadline



def remove_html_markup(s):
tag = False
quote = False
out = ""

for c in s:
    if c == '<' and not quote:
        tag = True
    elif c == '>' and not quote:
        tag = False
    elif c == '"' or c == "'" and tag:
        quote = not quote
    elif not tag:
        out = out + c
return out



def main():
    print remove_html_markup('xyz')
    print remove_html_markup('"<b>foo</b>"')
    print remove_html_markup("'<b>foo</b>'")



breakpoints = {9: True}
stepping = False



def debug(command, my_locals):
    global stepping
    global breakpoints

    if command.find(' ') > 0:
        arg = command.split(' ')[1]
    else:
        arg = None

    if command.startswith('s'):  # step
        stepping = True
        return True
    elif command.startswith('c'):  # continue
        stepping = False
        return True
    elif command.startswith('p'):    # print
        stepping = False
        return True

    elif command.startswith('q'):  # quit
        sys.exit(0)
    else:
        print "No such command", repr(command)

    return False


commands = ["p", "s", "p tag", "p foo", "q"]


def input_command():
    # command = raw_input("(my-spyder) ")
    global commands
    command = commands.pop(0)
    return command


def traceit(frame, event, trace_arg):
    global stepping

    if event == 'line':
        if stepping or breakpoints.has_key(frame.f_lineno):
            resume = False
            while not resume:
                print event, frame.f_lineno, frame.f_code.co_name, frame.f_locals
                command = input_command()
                resume = debug(command, frame.f_locals)
    return traceit



sys.settrace(traceit)
main()
sys.settrace(None)

输出应为

line 9 remove_html_markup {'s': 'xyz'}
line 10 remove_html_markup {'s': 'xyz', 'tag': False}
line 11 remove_html_markup {'quote': False, 's': 'xyz', 'tag': False}
line 13 remove_html_markup {'quote': False, 's': 'xyz', 'tag': False, 'out': ''}
line 14 remove_html_markup {'quote': False, 's': 'xyz', 'tag': False, 'c': 'x', 'out': ''}

但它返回

xyz
<b>foo</b>
'foo'

我需要知道如何解决这个问题,我是调试的新手,我真的需要学习调试以提高我的技能并减少修复错误的时间

1 个答案:

答案 0 :(得分:0)

经过努力,我意识到我的Python 2.7.5没有工作,当我将其更新为2.7.14但同样的情况发生了,然后我意识到在我的代码顶部有这条线

#!/usr/bin/env python

由于我使用的是Windows,这行代码甚至不存在,所以一旦删除它,事情就变得非常棒了,代码也运行了!