Skip to content

Instantly share code, notes, and snippets.

@mcchae
Created May 8, 2018 10:53
Show Gist options
  • Save mcchae/e163b017018c2026e110fd595889ae86 to your computer and use it in GitHub Desktop.
Save mcchae/e163b017018c2026e110fd595889ae86 to your computer and use it in GitHub Desktop.
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