Executing an external program in transit from Sublime Text

I am trying to write a plugin for Sublime that will read the text of the current line, execute this as a shell command and put the output of the command in the editor. This is what I have so far:

import sublime, sublime_plugin, os, os.path
import subprocess

def GetLineAtCursor(view):
    pos = view.sel()[0].a
    reg = view.line(pos)
    return view.substr(reg)

class ExecuteLineGetOutputCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        line = GetLineAtCursor(self.view).strip().split()
        output = subprocess.check_output(line,shell=True)
        self.view.insert(edit, 0, output)

This does not work. In particular, the call subprocess.check_output(...)does not work, although it works fine in the python interpreter. I put it in a try block, for example:

try:
    output = subprocess.check_output(line,shell=True)
except Exception as e:
    self.view.insert(edit, 0, str(e))

It produces the following output, apparently no matter what command I try to execute:

[WinError 6] The handle is invalid

Does anyone know what the problem is and how to fix it?

+4
source share
1 answer

Try the following:

def run(self, edit):
    line = GetLineAtCursor(self.view).strip().split()
    cmd = [line, 'attr1', 'attr2']

    # if windows
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, creationflags=subprocess.SW_HIDE)
    #else unix/macos
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)    

    output, stderr = p.communicate()

    if (stderr):
        print(stderr)
    self.view.insert(edit, 0, output)
+1
source

All Articles