Python 在升华文本路径中执行外部程序

Python 在升华文本路径中执行外部程序,python,python-3.x,sublimetext3,sublime-text-plugin,Python,Python 3.x,Sublimetext3,Sublime Text Plugin,我正在尝试为Sublime编写一个插件,它将读取当前行的文本,作为shell命令执行,并将命令的输出放入编辑器中。这就是我到目前为止所做的: 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 Exe

我正在尝试为Sublime编写一个插件,它将读取当前行的文本,作为shell命令执行,并将命令的输出放入编辑器中。这就是我到目前为止所做的:

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)
这是行不通的。具体来说,调用
subprocess.check_output(…)
是不起作用的,尽管它在python解释器中可以正常工作。我把它放在一个try块中,如下所示:

try:
    output = subprocess.check_output(line,shell=True)
except Exception as e:
    self.view.insert(edit, 0, str(e))
无论我尝试使用什么命令,它都会生成以下输出:

[WinError 6]句柄无效
有人知道问题是什么,以及如何解决吗?

试试这个:

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)