Created
May 8, 2018 10:53
-
-
Save mcchae/e163b017018c2026e110fd595889ae86 to your computer and use it in GitHub Desktop.
PyCharm debug with dynamic code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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