How can I create a build system in Sublime Text 3 where "cmd"
is replaced with a shebang if it exists?
More specifically, is there a way to alter the Python build system to use the version of Python specified in the shebang, and use a default if no shebang is present?
If think the only way to do this using a standard
.sublime-build
file is to pass your file to another script which then parses the shebang and passes it on to the correct Python version.Alternatively, you could specify build variants, but then you will have to choose the desired build variant manually.
Sublime build systems have an option named
target
which specifies aWindowCommand
that is to be invoked to perform the build. By default this is the internalexec
command. You can create your own command that would examine the file for a shebang and use that interpreter or some default otherwise.For example (caveat: I'm not super proficient in Python so this is probably quite ugly):
You would save this in
Packages/User
as a python file (e.g.shebanger.py
).This creates a new command named
shebanger
that collects the arguments it's been given, examines the file in the currently active view of the window the build is triggered in to see if the first line is a shebang, and then synthesizes the arguments needed for theexec
command and runs it.Since the default python build system assumes it is building the current file and passing
-u
as an argument, that's what this command replicates as well. Note however that this code is not 100% correct because any arguments in the shebang line will be ignored, but you get the general idea.In use, you would modify the default
Python.sublime-build
file to look like this:Notice that in the variant we override what the interpreter arguments are; you could also override the default interpreter there as well if desired.
My python.sublime-build
In windows I used py launcher to detect the versions according to the shebang