Formatting Stack Overflow questions using Python
<p>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:</p>

<pre><code># script.py
# usage: python3 script.py &gt; 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 &amp; descriptions and returns a Stack Overflow question"
    # get the code from the source script &amp; 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 &amp; 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 &amp; 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 &amp; 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 &amp; 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 &amp; print formatted SO question
print(stack_overflow_question_generator(question_params))
</code></pre>

<p>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:</p>

<pre><code>Traceback (most recent call last):
  File "script.py", line 19, in stack_overflow_question_generator
    __import__(source_module)
  File "/Users/alecrasmussen/script.py", line 86, in &lt;module&gt;
    print(stack_overflow_question_generator(question_params))
  File "/Users/alecrasmussen/script.py", line 28, in stack_overflow_question_generator
    raise UserWarning(no_error_message)
UserWarning: No exception raised by script.py
</code></pre>

<p>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.)</p>