Python 编辑器中的单元模式
在最近版本的MATLAB中,你可以通过按 Ctrl-Enter 来执行两行之间的代码,这两行是以 %%
开头的。这种代码区域被称为 代码单元,它可以让你快速测试和调试代码。
例如:
%% This is the beginning of the 1st cell
a = 5;
%% This is the end of the 1st cell and beginning of the 2nd cell
% This is just a comment
b = 6;
%% This is the end of the 2nd cell
有没有类似功能的Python编辑器呢?
编辑:我刚发现 Spyderlib 支持用F9执行“块”代码(用空行分隔的代码区域),但是正如 这个讨论 所提到的,这个功能目前还不是很稳定(尤其是在与循环结合使用时)。
7 个回答
3
Spyder3 和 PyCharm: #%% 或 # %%
Spyder3: 按 Ctrl + Enter 可以运行当前的代码块,按 Shift + Enter 则是运行当前的代码块并跳到下一个。
PyCharm: 按 Ctrl + Enter 可以运行代码并跳到下一个。
# %%
print('You are in cell 1')
# %%
print('You are in cell 2')
# %%
print('You are in cell 3')
5
在Spyder3中,一个“单元格”是指所有在以#%%
开头的行之间的代码。
你可以按Ctrl+Enter来运行一个单元格,或者按Shift+Enter来运行一个单元格并跳到下一个单元格。
7
Python的互动编辑器 IEP 有一种类似Matlab的方式来标记代码段,这种方式是通过在行首加上'##'来实现的。此外,默认的快捷键也是 Ctrl+Enter。
## Cell one
"""
A cell is everything between two commands starting with '##'
"""
a = 3
b = 4
print('The answer is ' + str(a+b))
## Cell two
print('Hello World')