Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PyCharm debug with dynamic code
#!/usr/bin/env python
# coding=utf8
################################################################################
import os
import importlib.util
################################################################################
def run(code):
cf = 'foo.py'
try:
with open(cf, 'w', encoding='utf8') as ofp:
ofp.write(code)
spec = importlib.util.spec_from_file_location("foo", cf)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.myrun()
finally:
if os.path.exists(cf):
os.unlink(cf)
################################################################################
def main():
code = """
def myrun():
def sum(i, j):
return i + j
# pdb.set_trace()
i = 1
j = 2
k = sum(i, j)
print('sum of %s, %s = %s' % (i, j, k))
"""
run(code)
################################################################################
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.