如何在jupyter笔记本中为SQL行魔术,单元魔术和自定义命令添加语法突出显示
技术问答
463 人阅读
|
0 人回复
|
2023-09-13
|
我正在寻找在jupyter笔记本中突出显示SQL代码的方法。我只能突出显示SQL单元魔术,而不能突出显示行魔术和自定义设置。
" W3 F9 o) b- M' o9 R7 `+ Z F3 P% cCase 1 (works)
+ B" g% Z4 d4 q3 U1 x: k8 jHighlight cell magic (cell startswith %%sql). `+ Z, l) A2 u) \6 [5 e
Ref: adding syntax highlighting to Jupyter notebook cell0 t, a2 N p! S; H3 G
magic. f2 G: C/ d0 ~3 l
require(['notebook/js/codecell'], function(codecell) {
" ^( Q x+ ]1 q codecell.CodeCell.options_default.highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;; h/ g2 b% Y/ f# q# b
Jupyter.notebook.events.one('kernel_ready.Kernel', function(){9 n) N D3 y/ M) R. |8 h2 P
Jupyter.notebook.get_cells().map(function(cell){
- Y7 o. u; G% ] g! W if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
, J9 X' D0 U) e2 `/ u) S* g });
1 l4 w M" \4 p$ k; c9 x0 ]});
% c4 H4 Y9 \8 B: {6 i( u* uCase 2(does not work)
, D, Z* B; [. ~& u7 v& ^Line Magic: line starts with %sql
5 d3 G; [/ }& j4 R/ JMy attempt: Change the regex to ^%sql but it did not work.
+ T0 T' A# n( @4 U1 f% ]3 ^%sql select * from Products limit 5;
4 r3 M8 }" P4 J. X3 c2 | b6 HCase 3 (does not work)& P4 }( t; h% K! J0 o
如何语法突出显示自定义单元格(单元格以## %%开头)我的尝试:尝试将正则表达式更改为^##%%sql
. G C% m$ @2 }7 X$ k##%%sql' t2 o6 b! g% Z% t7 ]+ E
q = " select * from customer limit 2;", X' Z6 L' r( E1 F& ^% P
execute_query(q,dbname)
! Q6 [2 L. }( _0 D" |Example image+ K+ O+ Y8 Z6 ]/ M/ O( z
In the image we can see that cell magic %sql commands are not highlighted. I
8 |: d6 ~4 h7 @- m! ~3 Pwant them to be highlighted.
4 w5 d+ Y a5 ~5 {; ^5 A9 G8 |1 c- W4 x; [8 }8 q' E% D- K; I
/ X; N0 Q- i* V" ]
1 Y: L+ h5 B! ]1 R7 o N
解决方案:/ B2 n4 e: W0 k: _" T' ^+ C/ C
, }- f* O/ _* h; @; A$ R, B$ ]; t, t. E' V9 r& i, [3 F, n
0 A" |) d* l9 v. F! l
像第三个单元格一样,这甚至适用于分配。当前无法使用多种语言突出显示。因此,无论采用哪种语法,都将是Python或SQL语法。whatever comes first., r* i B U! T
require(['notebook/js/codecell'], function (codecell) {- C* D- a2 ~5 }4 q" l
codecell.CodeCell.options_default.highlight_modes['magic_text/x-mssql'] = { 'reg': [/%?%sql/] };9 `' r4 I$ \) f1 R& r( d
Jupyter.notebook.events.one('kernel_ready.Kernel', function () {& ~1 ]6 m* B; g
Jupyter.notebook.get_cells().map(function (cell) {# | j; L4 b8 g: V9 R+ W) B& }
if (cell.cell_type == 'code') { cell.auto_highlight(); }
- k: v+ r/ y. q# I: m! Y });
+ i' A. s/ B a! ~$ H3 X* o5 G" b: q5 l });
4 `/ S5 i+ A& s0 E( w7 m. A# A}); |
|
|
|
|
|