如何在Sublime Text 3中创建一个构建系统,在存在shebang的情况下用"cmd"
替换它?
更具体地说,是否有一种方法可以修改Python构建系统,以使用shebang中指定的Python版本,并在没有shebang的情况下使用默认值?
如何在Sublime Text 3中创建一个构建系统,在存在shebang的情况下用"cmd"
替换它?
更具体地说,是否有一种方法可以修改Python构建系统,以使用shebang中指定的Python版本,并在没有shebang的情况下使用默认值?
target
的选项,它指定要调用的WindowCommand
来执行构建。默认情况下,这是内部的exec
命令。您可以创建自己的命令,该命令将检查文件中的shebang并使用该解释器或某些默认值。import sublime, sublime_plugin
class ShebangerCommand(sublime_plugin.WindowCommand):
def parseShebang (self, filename):
with open(filename, 'r') as handle:
shebang = handle.readline ().strip ().split (' ', 1)[0]
if shebang.startswith ("#!"):
return shebang[2:]
return None
def createExecDict(self, sourceDict):
current_file = self.window.active_view ().file_name()
args = dict (sourceDict)
interpreter = args.pop ("interpreter_default", "python")
exec_args = args.pop ("interpreter_args", ["-u"])
shebang = self.parseShebang (current_file)
args["shell_cmd"] = "{} {} \"{}\"".format (shebang or interpreter,
" ".join (exec_args),
current_file)
return args
def run(self, **kwargs):
self.window.run_command ("exec", self.createExecDict (kwargs))
Packages/User
目录下,文件名为Python文件(例如shebanger.py
)。shebanger
的新命令,它会收集给定的参数,检查触发构建的窗口中当前活动视图中的文件是否有shebang,并合成exec
命令所需的参数并运行它。-u
作为参数,因此该命令也会复制这一点。但是请注意,该代码不是100%正确的,因为shebang行中的任何参数都将被忽略,但是您可以得到一般的想法。Python.sublime-build
文件,使其如下所示:{
// WindowCommand to execute for this build
"target": "shebanger",
// Use this when there is no shebang
"interpreter_default": "python",
// Args to pass to the interpreter
"interpreter_args": ["-u"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"env": {"PYTHONIOENCODING": "utf-8"},
"variants":
[
{
"name": "Syntax Check",
"interpreter_args": ["-m py_compile"],
}
]
}
如果您想使用标准的.sublime-build
文件来实现这一点,那么唯一的方法是将您的文件传递给另一个脚本,该脚本然后解析shebang并将其传递给正确的Python版本。
或者,您可以指定构建变体,但这样您就必须手动选择所需的构建变体。
我的 python.sublime-build
{
"cmd": ["py", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python",
"shell":true
}