对于 jupyter sas_kernel,我正在为 nbconvert(版本 4.2.0)编写模板。基本布局如下:
{%- extends 'null.tpl' -%}
{# Comment block #}
{% block header %}
/* coding: SAS utf-8 */
{% endblock header %}
{% block in_prompt %}
/* In[{{ cell.execution_count if cell.execution_count else ' ' }}]: */
{% endblock in_prompt %}
{% block input %}
{{ cell.source | ipython2python | sas_magic_regex }}
{% endblock input %}
{% block markdowncell scoped %}
/*
{{ cell.source | comment_lines(prefix='*') }}
*/
{% endblock markdowncell %}
在块输入部分,我需要使用正则表达式来处理文本,ipython2python主要是处理魔术调用。我无法从字符串文件管理器中看到正则表达式函数,
所以我编写了自己的:
def sas_magic_regex(string:str) -> str:
""" Replace Python Magics with a commented out version or the SAS x command """
sas_magic=re.compile(r'^get_ipython.*?(\w+)\(\'(.*)\'\)')
newStr=sas_magic.search(string)
if len(newStr.groups())==2:
if newStr.group(1)=='system':
return 'x ' + newStr.group(2) + ';'
else:
return '/* Jupyter magic ' + string + ' */'
env = Environment()
env.filters['sas_magic_regex'] = sas_magic_regex
问题是 nbconvert 找不到这个 jinja 过滤器。我收到此错误消息:jinja2.exceptions.TemplateAssertionError: no filter named 'sas_magic_regex'