python - 如何创建打印变量的快捷方式(vscode)
问题描述
如何创建自定义快捷方式来生成将在 vscode 中打印所选变量的代码?
[1] arr = [1,2,3,4] # I press double left mouse button on 'arr'
[2] print(arr) # Then I press <magic shortcut> (Ctrl+p for example)
# And vscode generate [2] row automatically
您可以通过print()
.
解决方案
如果您不选择变量,而只是将光标放在行尾,则可以使用简单的键绑定来插入片段,而无需宏。键绑定:
{
"key": "alt+w",
"command": "editor.action.insertSnippet",
"args": {
// works with cursor end of line, no selection
// output: print(arr)
"snippet": "\n${TM_CURRENT_LINE/(\\s*)(\\w*)\\b.*/print($2)/}"
}
},
如果您想要此输出print(“arr”: arr)
,请使用此键绑定:
{
"key": "alt+w",
"command": "editor.action.insertSnippet",
"args": {
// works with cursor end of line, no selection
// output: print(“arr”: arr)
"snippet": "\n${TM_CURRENT_LINE/(\\s*)(\\w*)\\b.*/print(\"$2\": $2)/}"
}
},
对于这些更简单的版本,变量必须是行中的第一个单词。
较旧的答案:
不幸的是,这似乎很难用一个简单的片段来完成。将在光标所在的位置插入一个新的片段 - 并且在您选择的变量上的场景下 - 然后第一行的其余部分仍然存在于片段之后。
使用允许您执行多个命令(如多命令或其他命令)的宏扩展相对容易。
安装扩展程序后,在您的设置中:
"multiCommand.commands": [
{
"command": "multiCommand.printVariable",
"sequence": [
"editor.action.clipboardCopyAction",
"editor.action.insertLineAfter",
{
"command": "type",
"args": {
"text": "print("
}
},
"editor.action.clipboardPasteAction",
{
"command": "type",
"args": {
"text": ")"
}
},
]
}
},
然后在 keybindings.json 中设置一些键绑定:
{
"key": "alt+q",
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.printVariable" },
// use the following if you wish to limit the command to python files
"when": "resourceExtname == .py"
},
如演示 gif 所示,选定的文本可以位于该行的任何位置,如果该行紧接在print()
语句下方的代码将插入到您期望的位置。
注意:这会将您选择的变量保存到剪贴板,以便将其覆盖。
如果您的变量始终位于行首并被选中,则可以使用更简单的宏:
"multiCommand.commands": [
{
"command": "multiCommand.printVariable",
"sequence": [
{
"command": "editor.action.insertSnippet",
"args": {
// selected variable is at beginning of line
"snippet": "${TM_CURRENT_LINE}\nprint(${TM_SELECTED_TEXT})"
}
},
"cursorEndSelect", // select to end and delete
"editor.action.clipboardCutAction"
]
}
]
推荐阅读
- php - 如何注销会话然后登录另一个会话?
- reactjs - Multiple Material UI AppBar CSS conflict Caused By Postion Prop
- java - JPA 继承 @EntityGraph 包括可选的子类关联
- echarts - Echarts - 双 YAsix 不能使用不同的最小值/最大值
- math - 如果两个条件为真,如何翻转数字的符号?
- javascript - 如何创建一个在环 x9 上运行的圆圈?Javascript?
- android - Android:获取切换按钮操作而不是选定的导航项
- php - php如何防止多个用户同时登录?
- r - 我怎样才能获得夏皮罗威尔克测试
- javascript - 如何使用谷歌脚本替换字符串中的所有字符?