标签: traceback

Python:Traceback codecs.charmap_decode(input,self.errors,decoding_table)[0]

以下是示例代码,目的只是合并来自give文件夹及其子文件夹的文本文件.我偶尔会得到Traceback所以不知道在哪里看.还需要一些帮助来增强代码以防止空行被合并并在合并/主文件中不显示任何行.在合并文件之前,可能需要进行一些清理或者在合并过程中忽略空行,这可能是个好主意.

文件夹中的文本文件不超过1000行,但聚合主文件可以非常容易地跨越10000多行.

import os
root = 'C:\\Dropbox\\ans7i\\'
files = [(path,f) for path,_,file_list in os.walk(root) for f in file_list]
out_file = open('C:\\Dropbox\\Python\\master.txt','w')
for path,f_name in files:
    in_file = open('%s/%s'%(path,f_name), 'r')

    # write out root/path/to/file (space) file_contents
    for line in in_file:
        out_file.write('%s/%s %s'%(path,f_name,line))
    in_file.close()

    # enter new line after each file
    out_file.write('\n')

with open('master.txt', 'r') as f:
  lines = f.readlines()
with open('master.txt', 'w') as f:
  f.write("".join(L for L in lines if L.strip())) 



Traceback (most recent call last):
  File "C:\Dropbox\Python\master.py", line 9, in …
Run Code Online (Sandbox Code Playgroud)

python file-io traceback python-3.x python-unicode

3
推荐指数
2
解决办法
2万
查看次数

在 Python 中伪造回溯

我正在编写一个测试运行程序。我有一个可以捕获和存储异常的对象,稍后将其格式化为字符串作为测试失败报告的一部分。我正在尝试对格式化异常的过程进行单元测试。

在我的测试设置中,我不想实际抛出异常让我的对象捕获,主要是因为这意味着回溯将不可预测。(如果文件改变长度,回溯中的行号也会改变。)

如何将虚假回溯附加到异常,以便我可以断言它的格式化方式?这甚至可能吗?我正在使用 Python 3.3。

简化示例:

class ExceptionCatcher(object):
    def __init__(self, function_to_try):
        self.f = function_to_try
        self.exception = None
    def try_run(self):
        try:
            self.f()
        except Exception as e:
            self.exception = e

def format_exception_catcher(catcher):
    pass
    # No implementation yet - I'm doing TDD.
    # This'll probably use the 'traceback' module to stringify catcher.exception


class TestFormattingExceptions(unittest.TestCase):
    def test_formatting(self):
        catcher = ExceptionCatcher(None)
        catcher.exception = ValueError("Oh no")

        # do something to catcher.exception so that it has a traceback?

        output_str = format_exception_catcher(catcher)
        self.assertEquals(output_str,
"""Traceback (most recent …
Run Code Online (Sandbox Code Playgroud)

python testing unit-testing mocking traceback

3
推荐指数
1
解决办法
2091
查看次数

在python中格式化一个异常,包括除最后一个'n'回溯帧之外的所有异常

假设您有这样的设置:

def a():
    b()

def b():
    c()

def c():
    d()

def d():
    e()
Run Code Online (Sandbox Code Playgroud)

尝试调用a()将导致以下回溯:

Traceback (most recent call last):
  File "<pyshell#181>", line 1, in <module>
    a()
  File "<pyshell#87>", line 2, in a
    b()
  File "<pyshell#90>", line 2, in b
    c()
  File "<pyshell#93>", line 2, in c
    d()
  File "<pyshell#96>", line 2, in d
    e()
NameError: name 'e' is not defined
Run Code Online (Sandbox Code Playgroud)

有没有办法格式化异常,以便它只包括n回溯中的最后一帧?例如,如果n = 2,traceback将如下所示:

Traceback (most recent call last):
  File "<pyshell#93>", line 2, in c …
Run Code Online (Sandbox Code Playgroud)

python exception traceback

3
推荐指数
1
解决办法
228
查看次数

__init __()缺少3个必需的位置参数

我正在尝试为类编写代码,并且在类中遇到了巨大的麻烦.问题是我们用一个类编写脚本Car,将speed方法设置为'0',并在一系列十次迭代中显示速度(调用accelerationbrake每次调用五次).我得到的错误是:

Traceback (most recent call last): File "C:/Users/Brown Bear/Documents/Wake Tech/CIS115/Python Documents/Lab14P1.py", line 36, in <module> main() File "C:/Users/Brown Bear/Documents/Wake Tech/CIS115/Python Documents/Lab14P1.py", line 27, in main my_speed = Car() TypeError: __init__() missing 3 required positional arguments: 'make', 'model', and 'speed'

这是输出应该是什么的例子:

Enter model of your car: Prius
Enter make of your car: Toyota
Current speed: 5
Current speed: 10
Current speed: 15
Current speed: 20
Current speed: 25
Current speed: 20
Current speed: …
Run Code Online (Sandbox Code Playgroud)

python class object instance traceback

3
推荐指数
1
解决办法
1万
查看次数

Python3 - TypeError:“float”和“NoneType”的实例之间不支持“&gt;”

我最近参加了一门 Python 课程,我正在做的练习希望我找到最大和最小的数字。如果我输入一个“字符串”,那么它会提示“无效输入”。这是我到目前为止所得到的,但我收到了回溯错误:

Traceback (most recent call last):
    File "FindingSmallestLargestNum.py", line 15, in <module>
    if num > largest:
TypeError: '>' not supported between instances of 'float' and 
'NoneType'
Run Code Online (Sandbox Code Playgroud)

这是我的代码行:

largest = None
smallest = None

while True: 
    num = input("Enter a number: ")
    if num == "done": break
    try:
        num = float(num)
except:
    print("Invalid input")
    continue

    if smallest is None:
        smallest = num
    if num > largest:
        largest = num
    elif num < smallest:
        smallest = num

print("Maximum is",int(largest))
print("Minimum …
Run Code Online (Sandbox Code Playgroud)

traceback python-3.x

3
推荐指数
1
解决办法
1万
查看次数

为什么回溯打印早于打印 url?

据我所知,当运行以下代码时,print(url, end='')将首先打印一行。

然后requests.get(url)引发异常,从而触发traceback.print_exc().

但在我的测试中,traceback.print_exc()屏幕上的打印早于print(url, end='').

为什么?

另一方面,如果我用 替换traceback.print_exc()print('error occurred')它就会按照我的想法工作。

看来 的traceback.print_exc()优先级更高?

import traceback

import requests


url = 'http://www.szwb.gov.cn/wap/jggk/gzdt/201809/t20180919_14099889.htm'

try:
    print(url, end='')
    response = requests.get(url)
    # balabala
except Exception as e:
    traceback.print_exc()
    # print('error occurred.')
Run Code Online (Sandbox Code Playgroud)

python traceback

3
推荐指数
1
解决办法
576
查看次数

Windows 解释器上未定义 Namedtuple

我试图遵循的使用示例namedtuple( )文档,但我不断收到namedtuple is not defined

追溯

python tuples namedtuple traceback

3
推荐指数
1
解决办法
982
查看次数

从traceback获取最后一个函数的调用参数?

我可以获取traceback中调用的最后一个函数的参数吗?怎么样?

我想制作标准错误的捕获器以生成可读代码,同时向用户提供详细信息.

在下面的例子中,我希望GET_PARAMS返回一个提供给os.chown的参数元组.检查inspectAlex Martelli建议的模块,我找不到.

def catch_errors(fn):
    def decorator(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except (IOError, OSError):
            msg = sys.exc_info()[2].tb_frame.f_locals['error_message']
            quit(msg.format(SEQUENCE_OF_PARAMETERS_OF_THE_LAST_FUNCTION_CALLED)\
            + '\nError #{0[0]}: {0[1]}'.format(sys.exc_info()[1].args), 1)
    return decorator

@catch_errors
def do_your_job():
    error_message = 'Can\'t change folder ownership \'{0}\' (uid:{1}, gid:{2})'
    os.chown('/root', 1000, 1000) # note that params aren't named vars.

if __name == '__main__' and os.getenv('USERNAME') != 'root':
    do_your_job()
Run Code Online (Sandbox Code Playgroud)

(感谢Jim Robert为装饰师)

python exception-handling traceback

2
推荐指数
1
解决办法
1945
查看次数

py.test Tracebacks:突出显示我的代码,折叠框架框架

自从我使用 pytest 以来,我的测试的回溯太长了。

Pytests 包括周围的代码行和许多其他信息。

如果回溯线(框架)来自我的代码,我希望看到此信息。但我不想看到它,如果它来自库或框架。

我找不到过滤或折叠框架的方法。

有什么提示吗?

8 年后更新:我认为是时候告别 ASCII 并拥抱 html 了。使用 html,您可以展开/折叠部分(就像在很棒的 django 调试视图中一样)。

不幸的是,似乎没有 pytest 输出可以为您提供像哨兵那样的良好界面。

python filter stack-trace traceback pytest

2
推荐指数
1
解决办法
502
查看次数

维基百科消歧错误

我最近一直在使用维基百科模块来确定一个随机的维基百科页面。

我一直在用一个非常大的单词列表和 random.choice() 模块来做这个:

words=open("words.txt","r")
words=words.read()

words=words.split()    

text=random.choice(words)

string=random.choice(wikipedia.search(text))

p = wikipedia.page(string)
Run Code Online (Sandbox Code Playgroud)

该系统似乎最常工作,但偶尔会出现错误:

Traceback (most recent call last):
  File "/home/will/google4.py", line 25, in <module>
    p = wikipedia.page(string)
  File "/usr/local/lib/python2.7/dist-packages/wikipedia/wikipedia.py", line 276, in page
    return WikipediaPage(title, redirect=redirect, preload=preload)
  File "/usr/local/lib/python2.7/dist-packages/wikipedia/wikipedia.py", line 299, in __init__
    self.__load(redirect=redirect, preload=preload)
  File "/usr/local/lib/python2.7/dist-packages/wikipedia/wikipedia.py", line 393, in __load
    raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to)
DisambiguationError: "The Scarf" may refer to: 
The Scarf (film)
The Scarf (opera)
Scarf (disambiguation)
Arthur Stewart King Scarf  
Run Code Online (Sandbox Code Playgroud)

无论如何,我可以绕过它吗?

python wikipedia-api traceback

2
推荐指数
1
解决办法
6271
查看次数