Skip to main content
 首页 » 编程设计

python之像在记事本中一样按 F5 插入日期时间

2025年01月19日18Free-Thinker

我在首选项 - 浏览包 - 用户(文件夹)中制作了这个 whatever.py 文件

import sublime, sublime_plugin, time 
class InsertDatetimeCommand(sublime_plugin.TextCommand): 
def run(self, edit): 
    sel = self.view.sel(); 
    for s in sel: 
        self.view.replace(edit, s, time.strftime( '%H:%M %d/%m/%Y' )) 

然后

在首选项 - 键绑定(bind) - 用户中,添加了这一行:

{ "keys": ["f5"], "command": "insert_datetime"} 

这按 F5 键按预期工作,我可以插入日期时间,但是当我这样做时,这个日期时间被选中,当我按 enter 键转到换行符时,它被删除了。您知道我应该更改上面代码的哪一部分以在按 F5 后不选择所有日期时间字符串吗?

请您参考如下方法:

我建议使用 view.insert 在选择的第二个末端添加字符串:

class InsertDatetimeCommand(sublime_plugin.TextCommand): 
    def run(self, edit): 
        sel = self.view.sel() 
        for s in sel: 
            self.view.insert(edit, s.b, time.strftime( '%H:%M %d/%m/%Y' )) 

replace 的问题是您要用 Selection 替换区域。因此,在运行该命令后,时间字符串被选中,因此当您按下 Enter 时它将被替换。您可以执行类似 sel.clear() 的操作或修改每个区域以修复它。

更新:
正如 OdatNurd 所说,在这种情况下使用 s.a 会很困惑。使用 s.b 会更一致。