问题
I am very new to programming and I using "Learn Python the hard way" and I find it very helpful.
One of the questions in the book was to run just one line, which I find impossible to do in Sublime Text 3. I have tried to google, but I can only find for Sublime Text 2 and some solutions that I was unable to make work.
I don't just use the default build that comes with Sublime Text 3, is there a way to mark some lines of the .py file in Sublime and build just those lines? Instead of the whole file when I press "cmd+b"?
Any help would be appreciated, thank you.
回答1:
Here's a little plugin to acomplish what you're asking for:
class RunSelectionsWithPythonCommand(sublime_plugin.TextCommand):
def run(self, edit, **kwargs):
import re
import tempfile
chunks = []
for region in self.view.sel():
chunks.append(self.view.substr(region))
if self.view.file_name():
working_dir = os.path.dirname(self.view.file_name())
else:
working_dir = os.getcwd()
chunks = "\n".join(chunks)
lines = filter(
None, [l for l in chunks.split("\n") if l.strip() != ""]
)
source_code = "\n".join(lines)
with tempfile.NamedTemporaryFile(suffix='.py', mode='w', delete=False) as f:
f.write(source_code)
window = sublime.active_window()
window.run_command("exec", {
"shell_cmd": "python {}".format(f.name),
"working_dir": working_dir,
"quiet": False
})
def is_enabled(self):
return len(self.view.sel()) > 0
Here's a little demo:
Because you're learning python the hard way I'll leave as an exercise to figure out how to install & use the above plugin... One hint, make sure python is available on the SublimeText process.
来源:https://stackoverflow.com/questions/50900175/build-just-one-line-in-sublime-text-3-python