gpt4 book ai didi

c++ - Sublime Text 3 - 在终端编译运行c++程序(路径包含空格)

转载 作者:行者123 更新时间:2023-11-30 02:25:34 25 4
gpt4 key购买 nike

我使用的是 Ubuntu 16.04。我使用 Sublime Text 3,我可以编译 c++ 程序并在终端中运行它。以下是脚本。

{
"cmd": ["g++", "$file", "-o", "${file_path}/${file_base_name}"],
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c, source.c++, source.cxx, source.cpp",
"variants":
[
{
"name": "RunInShell",
"shell": true,
"cmd": ["gnome-terminal -e 'bash -c \"${file_path}/${file_base_name};echo; echo Press ENTER to continue; read line;exit; exec bash\"'"]
}
]
}

但是,当 C++ 程序的路径包含空格(如 /algorithms/Search in Rotated Sorted Array)时,脚本无法运行!

bash:/media/algorithms/Search: No such file or directory shows in the terminal, when I using RunInShell.

我正在尝试修改脚本,例如插入单引号。

"cmd": ["gnome-terminal -e 'bash -c\"'${file_path}/${file_base_name}';echo; echo 按 ENTER 继续;读行;退出;执行 bash\"'"]

但它不起作用。

我想知道如何修改脚本以使其正常运行。

最佳答案

If we look at the documentation on Build Systems, we see that we can use snippet substitution in the variables used in the build system.

因此,我们可以escape each space to a backslash and a space, for use in Bash .首先在构建系统之外使用它可能更容易,例如通过在 ST (Python) 控制台中键入以下内容:

import os.path; file_path = '/algorithms/Search in Rotated Sorted Array'; file_name = os.path.basename(file_path); sublime.expand_variables(r'${file_path/ /\\ /g}/${file_base_name/ /\\ /g}', { 'file_path': os.path.dirname(file_path), 'file': file_path, 'file_name': file_name, 'file_extension': os.path.splitext(file_name)[1], 'file_base_name': os.path.splitext(file_name)[0], 'packages': sublime.packages_path() })

请注意,上面包含的变量比我们实际需要的要多,但实际上并不包括 all the variables available from the build system , 但对于这个例子来说已经足够了,如果你想进一步试验,可以很容易地添加它们。检查ST API Reference有关详细信息,特别是缺少的项目是 Window 类的一部分。

无论如何,我们从中得到的输出是:

'/algorithms/Search\\ in\\ Rotated\\ Sorted\\ Array'

(请记住,这是一个 Python 字符串,所以两个斜线是一个转义码,代表一个斜线。)

所以我们在这里看到的是${file_path//\\\\/g}。这告诉 ST 的是获取 file_path 变量的值并对其运行正则表达式替换。它应该用斜杠后跟空格替换空格。末尾的 /g 是全局正则表达式修饰符标志,告诉它不要在第一次匹配/替换时停止,以确保它替换所有空格。

现在,将其插入您的构建系统:

"cmd": ["gnome-terminal -e 'bash -c \"${file_path/ /\\\\ /g}/${file_base_name/ /\\\\ /g};echo;  echo Press ENTER to continue; read line;exit; exec bash\"'"]

请注意,我们有 4 个斜杠 - 在我展示用于测试的 Python 代码和 JSON 字符串中都有。这是因为前两个斜杠是一个转义序列,它告诉 JSON/Python 使用文字斜杠。然后我们想再次执行相同的操作,以便正则表达式模式将使用文字斜杠。

关于c++ - Sublime Text 3 - 在终端编译运行c++程序(路径包含空格),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44050850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com