python期望输出隐藏,用注释注释Python print()输出

给定带有print()语句的

Python脚本,我希望能够运行脚本并在显示每个语句输出的每个语句后插入注释.要演示,请使用名为example.py的脚本:

a, b = 1, 2

print('a + b:', a + b)

c, d = 3, 4

print('c + d:', c + d)

期望的输出是:

a, b = 1, 2

print('a + b:', a + b)

# a + b: 3

c, d = 3, 4

print('c + d:', c + d)

# c + d: 7

这是我的尝试,适用于上面的简单示例:

import sys

from io import StringIO

def intercept_stdout(func):

"redirect stdout from a target function"

def wrapper(*args, **kwargs):

"wrapper function for intercepting stdout"

# save original stdout

original_stdout = sys.stdout

# set up StringIO object to temporarily capture stdout

capture_stdout = StringIO()

sys.stdout = capture_stdout

# execute wrapped function

func(*args, **kwargs)

# assign captured stdout to value

func_output = capture_stdout.getvalue()

# reset stdout

sys.stdout = original_stdout

# return captured value

return func_output

return wrapper

@intercept_stdout

def exec_target(name):

"execute a target script"

with open(name, 'r') as f:

exec(f.read())

def read_target(name):

"read source code from a target script & return it as a list of lines"

with open(name) as f:

source = f.readlines()

# to properly format last comment, ensure source ends in a newline

if len(source[-1]) >= 1 and source[-1][-1] != '\n':

source[-1] += '\n'

return source

def annotate_source(target):

"given a target script, return the source with comments under each print()"

target_source = read_target(target)

# find each line that starts with 'print(' & get indices in reverse order

print_line_indices = [i for i, j in enumerate(target_source)

if len(j) > 6 and j[:6] == 'print(']

print_line_indices.reverse()

# execute the target script and get each line output in reverse order

target_output = exec_target(target)

printed_lines = target_output.split('\n')

printed_lines.reverse()

# iterate over the source and insert commented target output line-by-line

annotated_source = []

for i, line in enumerate(target_source):

annotated_source.append(line)

if print_line_indices and i == print_line_indices[-1]:

annotated_source.append('# ' + printed_lines.pop() + '\n')

print_line_indices.pop()

# return new annotated source as a string

return ''.join(annotated_source)

if __name__ == '__main__':

target_script = 'example.py'

with open('annotated_example.py', 'w') as f:

f.write(annotate_source(target_script))

但是,对于包含跨越多行的print()语句以及不在行开头的print()语句的脚本,它会失败.在最好的情况下,它甚至可以用于函数内的print()语句.请看以下示例:

print('''print to multiple lines, first line

second line

third line''')

print('print from partial line, first part') if True else 0

1 if False else print('print from partial line, second part')

print('print from compound statement, first part'); pass

pass; print('print from compound statement, second part')

def foo():

print('bar')

foo()

理想情况下,输出看起来像这样:

print('''print to multiple lines, first line

second line

third line''')

# print to multiple lines, first line

# second line

# third line

print('print from partial line, first part') if True else 0

# print from partial line, first part

1 if False else print('print from partial line, second part')

# print from partial line, second part

print('print from compound statement, first part'); pass

# print from compound statement, first part

pass; print('print from compound statement, second part')

# print from compound statement, second part

def foo():

print('bar')

foo()

# bar

但上面的脚本就像这样破坏它:

print('''print to multiple lines, first line

# print to multiple lines, first line

second line

third line''')

print('print from partial line, first part') if True else 0

# second line

1 if False else print('print from partial line, second part')

print('print from compound statement, first part'); pass

# third line

pass; print('print from compound statement, second part')

def foo():

print('bar')

foo()

什么方法可以使这个过程更加健壮?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值