简体   繁体   English

Python 导师 + Google Colab

[英]Python Tutor + Google Colab

Preambula.序言。 I'm trying to use Google Colab to teach students Python. The problem is, there is no nice tool to visualize code execution.我正在尝试使用 Google Colab 来教学生 Python。问题是,没有很好的工具来可视化代码执行。 I tried to use Python Tutor by integrating it with the Google Colab, namely created a "magic command"我尝试通过将 Python Tutor 与 Google Colab 集成来使用它,即创建了一个“魔术命令”

from IPython.core.magic import  Magics, magics_class, cell_magic, line_magic

@magics_class
class Helper(Magics):

  def __init__(self, shell=None,  **kwargs):
    super().__init__(shell=shell, **kwargs)

  @cell_magic
  def debug_cell_with_pytutor(self, line, cell):
    import urllib.parse
    url_src = urllib.parse.quote(cell)
    str_begin = '<iframe width="1000" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code='
    str_end   = '&cumulative=false&py=3&curInstr=0"></iframe>'
    import IPython
    from google.colab import output
    display(IPython.display.HTML(str_begin+url_src+str_end))

get_ipython().register_magics(Helper)

that can be later used as以后可以用作

%%debug_cell_with_pytutor

total_list = []
for i in range(3):
  total_list.append(i)
total_list

The problem.问题。 There are actually two problems:其实有两个问题:

  • Python Tutor often refuses to process not-so-complicated code like creating a class with few methods. Python 导师经常拒绝处理不那么复杂的代码,比如用很少的方法创建 class。 On the other hand, I was able to start Python Tutor locally and it did not fail.另一方面,我能够在本地启动 Python Tutor 并且没有失败。
  • I'm not happy with the fact that two different Pythons are used -- the one in Colab and the one in Python Tutor我对使用两种不同的 Python 感到不满意——一种在 Colab 中,另一种在 Python Tutor 中

What help am I seeking for.我在寻求什么帮助。 I would like to either start Python Tutor in Google Colab, or find any other nice visualization tool that may work in Colab.我想在 Google Colab 中启动 Python Tutor,或者寻找可以在 Colab 中使用的任何其他不错的可视化工具。

Thank you in advance!先感谢您!

UPDATE更新

At the end of the day I was able to find some solution, but it is quite messy.在一天结束时,我找到了一些解决方案,但它非常混乱。 I'll be glad if anyone proposes something better.如果有人提出更好的建议,我会很高兴。

At the moment the code looks like目前代码看起来像

#@title #Helper functions (debugger)

!curl -O https://raw.githubusercontent.com/fbeilstein/machine_learning/master/pytutor/data_begin.html
!curl -O https://raw.githubusercontent.com/fbeilstein/machine_learning/master/pytutor/data_end.html
!curl -O https://raw.githubusercontent.com/fbeilstein/machine_learning/master/pytutor/pg_encoder.py
!curl -O https://raw.githubusercontent.com/fbeilstein/machine_learning/master/pytutor/pg_logger.py

from IPython.core.magic import  Magics, magics_class, cell_magic, line_magic

@magics_class
class Helper(Magics):

  def __init__(self, shell=None,  **kwargs):
    super().__init__(shell=shell, **kwargs)
    with open('data_begin.html', 'r') as f_in:
      lines = f_in.readlines()
      self.begin_debug = "".join(lines)
    with open('data_end.html', 'r') as f_in:
      lines = f_in.readlines()
      self.end_debug = "".join(lines)

  @cell_magic
  def debug_cell_with_pytutor(self, line, cell):
    import json
    import bdb
    from pg_logger import PGLogger
    import IPython
    from google.colab import output

    def cgi_finalizer(input_code, output_trace):
      ret = dict(code=input_code, trace=output_trace)
      json_output = json.dumps(ret, indent=None) # use indent=None for most compact repr
      display(IPython.display.HTML("<html>" + self.begin_debug + json_output + self.end_debug + "</html>"))


    logger = PGLogger(cumulative_mode=False,
                  heap_primitives=False, 
                  show_only_outputs=False, 
                  finalizer_func=cgi_finalizer,
                  disable_security_checks=True,
                  allow_all_modules=True,
                  probe_exprs=False)

    try:
      logger._runscript(cell)
    except bdb.BdbQuit:
      print("INTERNAL ERROR OCCURED")
    finally:
      logger.finalize()

## use ipython load_ext mechanism here if distributed
get_ipython().register_magics(Helper)

Helper files are stored in my GitHub repository for the ML course.帮助程序文件存储在我的 GitHub 机器学习课程存储库中。 I created them basing on GraphTerm ideas and sources from PyTutor repository .我根据GraphTerm 的想法和来自PyTutor 存储库的资源创建了它们。 You can find some examples of usage in Lecture two "Python", but there's quite a lot of material, thus it may take some time to find them.在第二讲“Python”中可以找到一些使用示例,但是资料比较多,可能需要一些时间才能找到。

Try your existing code (the following part) with %%debug_cell_with_pytutor before it:在它之前使用%%debug_cell_with_pytutor尝试您现有的代码(以下部分):

from IPython.core.magic import  Magics, magics_class, cell_magic, line_magic

@magics_class
class Helper(Magics):

  def __init__(self, shell=None,  **kwargs):
    super().__init__(shell=shell, **kwargs)

  @cell_magic
  def debug_cell_with_pytutor(self, line, cell):
    import urllib.parse
    url_src = urllib.parse.quote(cell)
    str_begin = '<iframe width="1000" height="500" frameborder="0" src="https://pythontutor.com/iframe-embed.html#code='
    str_end   = '&cumulative=false&py=3&curInstr=0"></iframe>'
    import IPython
    from google.colab import output
    display(IPython.display.HTML(str_begin+url_src+str_end))

get_ipython().register_magics(Helper)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM