python读取文件数据堆栈溢出的原因_使用Python格式化堆栈溢出问题

# script.py

# usage: python3 script.py > stack_overflow_question.txt

from os.path import basename

from traceback import format_exc

def stack_overflow_question_generator(q_params):

"takes a source script & descriptions and returns a Stack Overflow question"

# get the code from the source script & pad each line with spaces

with open(q_params['source']) as f:

source = f.readlines()

code = ''.join(4 * ' ' + i for i in source)

# run the source script and get the traceback object

try:

trace_obj = None

try:

source_module = q_params['source'][:q_params['source'].index('.')]

__import__(source_module)

except Exception as e:

raise RuntimeError from e

except RuntimeError:

trace_obj = format_exc()

# raise a warning if the source script doesn't raise an error

if not trace_obj:

no_error_message = 'No exception raised by ' + q_params['source']

raise UserWarning(no_error_message)

# break the trace up into lines

trace_lines = trace_obj.split('\n')

# find the first line in the trace from the source and target it & its index

for i, t in enumerate(trace_lines):

if q_params['source'] in t:

target_line = t

index_one = i + 1

break

# find the first line of the outer trace and target its index

break_trace = ' '.join(['The above exception was the direct',

'cause of the following exception:'])

index_two = trace_lines.index(break_trace) - 1

# find the source script name in the target line & rebuild it with that name

quotes_index = [i for i, x in enumerate(target_line) if x == '"'][:2]

source_name = basename(target_line[quotes_index[0] + 1:quotes_index[1]])

filename = ''.join([' File "', source_name, target_line[quotes_index[1]:]])

# format the source traceback as a string & pad each line with spaces

trace = '\n'.join(4 * ' ' + i

for i in [trace_lines[0],

filename] + trace_lines[index_one:index_two])

# build and return the question formatted as a string

return '\n'.join([q_params['issue'], code, q_params['error'], trace,

q_params['request']])

# Example: set source script & other question params (issue, error, request):

question_params = {

'source': 'script.py',

'issue': ' '.join(['I\'m working on a script that will run another script',

'and automatically generate a formatted Stack Overflow',

'question based on the problem the script is having.',

'I\'d like to be able to provide accurate code samples',

'and tracebacks while avoiding all the copying and',

'pasting. Here\'s what I have so far:\n']),

'error': ' '.join(['However, when the source script doesn\'t actually',

'raise an exception, the question-generator script',

'can\'t really format the question appropriately and',

'just raises a warning:\n']),

'request': ' '.join(['Is there a better way for this script to generate',

'questions when the original script doesn\'t raise',

'any errors but still has some issue? I\'d also love',

'to see any implementations that accomplish the task',

'more efficiently or that improve the quality of the',

'question. (Also, apologies if this question is',

'better suited to stack overflow meta or code review;',

'I figured it made more sense here since I\'m trying',

'to build a tool in python for formatting output from',

'a python script.)'])

}

# Generate & print formatted SO question

print(stack_overflow_question_generator(question_params))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值