Skip to main content
 首页 » 编程设计

python之ipython之在任何光标位置强制执行表达式

2025年01月19日13开发

我有 ipython 5.3.0,当我在表达式中间时(光标标记为 <cursor>),例如:

In [69]: x = np.arange(<cursor>1, 21, 2).reshape(2, 5) 

比按 enter 将此行分成两行。

In [69]: x = np.arange(                        
    ...: 1, 21, 2).reshape(2, 5) 

但是当我在其他地方有光标时:

 In [69]: x = np.<cursor>arange(1, 21, 2).reshape(2, 5) 

它执行表达式。

哪个键盘快捷键在不考虑光标位置的情况下强制执行表达式?

我尝试了 CTRL + ENTER 或 SHIFT + ENTER 但没有一个适用于第一个示例。

请您参考如下方法:

This was fixed in IPython 5.4 .早些时候,没有办法修补/monkey-patching at startup ,但有一个简单的解决方法。

这是 5.4.1 的相关逻辑,在 IPython/terminal/shortcuts.py 中。带有引用第一个链接上的问题的评论的片段是修复。

def newline_or_execute_outer(shell): 
    def newline_or_execute(event): 
        """When the user presses return, insert a newline or execute the code.""" 
        b = event.current_buffer 
        d = b.document 
 
        if b.complete_state: 
            cc = b.complete_state.current_completion 
            if cc: 
                b.apply_completion(cc) 
            else: 
                b.cancel_completion() 
            return 
 
        # If there's only one line, treat it as if the cursor is at the end. 
        # See https://github.com/ipython/ipython/issues/10425 
        if d.line_count == 1: 
            check_text = d.text 
        else: 
            check_text = d.text[:d.cursor_position] 
        status, indent = shell.input_splitter.check_complete(check_text + '\n') 
 
        if not (d.on_last_line or 
                d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end() 
                ): 
            b.insert_text('\n' + (' ' * (indent or 0))) 
            return 
 
        if (status != 'incomplete') and b.accept_action.is_returnable: 
            b.accept_action.validate_and_handle(event.cli, b) 
        else: 
            b.insert_text('\n' + (' ' * (indent or 0))) 
    return newline_or_execute 

如您所见,操作取决于光标与代码标记相关的位置。

因此,如果您有一个完整的语句,您可以通过在 Enter 之前按 End 来强制执行。