atomic44 atomic44 - 1 year ago 78
Python Question

Run external python script from Sublime Text passing active file as argument

I have a some python script called somewhere on the disk, which is for processing text file in some way (and it uses more external libraries). Now I call it from console with passing a filename as argument.

Because I'm running this script often, during the editing the document itself, I would like to be able to call the script straight from the Sublime Text, passing active file as argument, so I can call it by one click without leaving the window.

But I haven't found a way how to call external python script from Sublime Text plugin. Can you give me a clue? Is that even possible?

Answer Source

One of way to doing this is by calling python with arguments through cmd.exe using subprocess module, with sending the file name of active file as argument for python program.

import sublime, sublime_plugin
import subprocess

class ExecuteExternalProgramCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        exec_file = "C:\Path\To\My\Program\"
        command  = ["cmd.exe", "/c", "python", exec_file, self.view.file_name()]

Save it to your Sublime Text User plugins folder and then put keyboard shortcut to your User Keymap, for example

{"keys": ["ctrl+shift+e"], "command": "execute_external_program"},