【问题标题】:Sublime Text 3 - compile and run c++ program(the path contains space) in terminalSublime Text 3 - 在终端编译和运行 c++ 程序(路径包含空格)
【发布时间】:2017-10-18 10:49:03
【问题描述】:

我使用的是 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 在我使用 RunInShell 时显示在终端中。

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

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

但它不起作用。

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

【问题讨论】:

  • 您可能需要在 ${file_path}/${file_base_name} 部分周围额外引用。
  • 你的想法是对的,但是这部分的附加引号与前面的引号匹配。所以它不起作用。

标签: c++ bash ubuntu terminal sublimetext3


【解决方案1】:

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 使用文字斜杠。然后我们想再次做同样的事情,以便正则表达式模式将使用文字斜线。

【讨论】:

  • 酷!你的解释很清楚。而且修改后效果很好。谢谢!
猜你喜欢
  • 2014-02-07
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 2013-01-15
  • 2015-12-01
  • 2016-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多