print()
문장을 가진 파이썬 스크립트가 주어지면 스크립트를 실행하고 각각의 결과를 보여주는 각 문장 다음에 주석을 삽입하고 싶습니다.주석으로 파이썬 print() 출력에 주석 달기
a, b = 1, 2
print('a + b:', a + b)
c, d = 3, 4
print('c + d:', c + d)
가 원하는 출력은 다음과 같습니다 : 입증하기 위해, example.py
이름이 스크립트를 가지고
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))
:
a, b = 1, 2
print('a + b:', a + b)
# a + b: 3
c, d = 3, 4
print('c + d:', c + d)
# c + d: 7
다음은 위와 같은 간단한 예제를 작동 나의 시도이다 그러나 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()
더 튼튼한가? 공급 때
'def foo (a, b) : print (a, b)'와 같은 상황에서'foo'가 여러 번 호출 될 수 있다고 예상 할 수있는 것은 무엇입니까? – Brian
미리 값을 모르는 곳에 인쇄물을 어떻게 표시하려고합니까? ex print (randint (0,100))? – xgord
@xgord 여전히 표시되지만 각 런스 루어마다 다를 수 있습니다. 나는 매번 결과가 같은 경우에 주로 사용하는 것이지만, 예제 출력을 보여주기에는 여전히 유용 할 수 있습니다. – Alec