Skip to content

Instantly share code, notes, and snippets.

@harukaeru
Created September 11, 2022 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harukaeru/8dd8413a755e089bf9634cc4602702ef to your computer and use it in GitHub Desktop.
Save harukaeru/8dd8413a755e089bf9634cc4602702ef to your computer and use it in GitHub Desktop.
profile the lines after tampering the original file
func_wrapper_line = '@profile\ndef main():\n'
lines = list(open('main.py').readlines())
insert_pos = 0
if lines[0].startswith('#!'):
insert_pos = 1
generated_lines = []
for i, line in enumerate(lines):
if i == insert_pos:
generated_lines.append(func_wrapper_line)
if i < insert_pos:
generated_lines.append(line)
if i >= insert_pos:
if line.startswith('def'):
generated_lines.append(' @profile\n' + ' ' + line)
else:
generated_lines.append(' ' + line)
generated_codes = ''.join(generated_lines)
print(generated_codes)
gen = compile(generated_codes, 'kerorin.py', 'exec')
data = {}
exec(gen, data)
# print(data['main'])
with open('kerorin.py', 'w') as f:
f.write(generated_codes)
main_func = data['main']
print('---------- Result -----------')
main_func()
print('---------- END ------------')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment