在Sublime Tex的路径中执行外部程序

2024-04-26 13:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为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解释器中工作得很好。我把它放在一个试块里,像这样:

^{pr2}$

不管我尝试什么命令,它都会产生以下输出:

[WinError 6] The handle is invalid

有人知道问题是什么,以及如何解决它吗?在


Tags: posimport命令selfviewoutputosdef
1条回答
网友
1楼 · 发布于 2024-04-26 13:28:42

试试这个:

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)

相关问题 更多 >