从Sublime Text运行外部python脚本,将活动文件作为参数

时间:2016-05-10 23:43:19

标签: python sublimetext3 sublimetext

我在磁盘上的某处有一个名为spc.py的python脚本,用于以某种方式处理文本文件(并且它使用更多的外部库)。现在我通过传递文件名作为参数从控制台调用它。

因为我经常运行这个脚本,在编辑文档本身时,我希望能够直接从Sublime Text调用脚本,将活动文件作为参数传递,所以我可以一键调用它离开窗户。

但我还没有找到如何从Sublime Text插件调用外部python脚本的方法。你能给我一个线索吗?这甚至可能吗?

3 个答案:

答案 0 :(得分:2)

执行此操作的方法之一是使用子进程模块通过cmd.exe调用带有参数的python,并将活动文件的文件名作为python程序的参数发送。

import sublime, sublime_plugin
import subprocess

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

将其保存到Sublime Text User插件文件夹,然后将键盘快捷键放到用户键盘上,例如

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

答案 1 :(得分:1)

你可以:

  • 创建一个custom build system,接受当前文件作为参数。
  • 创建一个plugin,用于执行当前文件中的文本。

答案 2 :(得分:0)

您可以使用提供的答案here来获取当前sublime窗口的文件名。除此之外,您只需要一个接受路径作为输入参数的方法,并从那里做您需要做的事情。

// Read the given file
let file = CsvFile.Load("c:/test.csv")

// Look at the parsed headers and find the index of column "A"
let aIdx = file.Headers.Value |> Seq.findIndex (fun k -> k = "A")

// Iterate over rows and print A values
for r in file.Rows do
  printfn "%A" (r.Item(aIdx))