Skip to content

VSCode 自定义 tasks

创建 tasks.json 文件

在 Windows 下,位于:

  • C:\Users\<username>\AppData\Roaming\Code\User\tasks.json

例如,需要创建一个自动复制当前文件相对路径和文件内容的任务,可以使用以下配置:

json
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "echo Hello"
        },
        {
            "label": "Copy Relative Path and Content to Clipboard",
            "type": "shell",
            "command": "python",
            "args": [
                "~/scripts/copy_path_and_content.py",
                "${workspaceFolder}",
                "${relativeFile}"
            ],
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

创建脚本

假如当前 vscode 窗口运行于远程 Linux 下,那么需要将脚本放置在远程服务器上:

  • ~/scripts/copy_path_and_content.py
py
import sys
import os


def main():
    workspace_folder = sys.argv[1]
    relative_file = sys.argv[2]
    relative_path = os.path.join(workspace_folder, relative_file)

    try:
        with open(relative_path, "r") as file:
            file_content = file.read()
    except Exception as e:
        print(f"Error reading file: {e}")
        return

    formatted_string = f"here is `{relative_file}`:\n```\n{file_content}\n```\n\n"
    output_file_path = os.path.expanduser("~/scripts/copied.txt")
    try:
        with open(output_file_path, "w") as output_file:
            output_file.write(formatted_string)
        print(f"Content written to {output_file_path}.")
    except Exception as e:
        print(f"Error writing to file: {e}")


if __name__ == "__main__":
    main()

运行

ctrl + shift + p,选择 Tasks: Run task > copy_path_and_content

或者按 ctrl + shift + b 快速运行上次使用的任务。