简体   繁体   中英

Build just one line in Sublime Text 3 - python

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM