sublime 插件 用于运行nodejs

写在前面的话

sublime 是有nodejs插件的,但是查看输出都是等node程序结束之后才显示,不能时时输出. 所以决定写一个小插件

实现

很简单了,直接上代码就能看明白了

import sublime, sublime_plugin,inspect,sys,os
import subprocess
import threading
import time

"""
	定义一个停止线程和子进程的方法,
	并清除追加到view的标记
"""
def stopThread(view):
	if hasattr(view.m_thread,"p"):
		print(view.m_thread.p.pid)
		view.m_thread.p.kill();
		view.m_thread.p.terminate();
		#print("TASKKILL /F /PID {pid} /T".format(pid=view.m_thread.p.pid))
		# subprocess.Popen("TASKKILL /F /PID {pid} /T".format(pid=view.m_thread.p.pid),shell=True)
	delattr(view,"m_thread")

""" 
	定义一个追加信息到输出窗口的command 
	方便我们抓到node输出时显示到输出窗口
"""
class AppendContentCommand(sublime_plugin.TextCommand):
	def run(self, edit,content):
		self.view.set_read_only(False)
		self.view.insert(edit,self.view.size(), content)
		self.view.set_read_only(True)	

IS_WIN32 = 'win32' in str(sys.platform).lower()

"""
	定义一个线程 运行command并抓取输出到调试窗口
	如果是win32就隐藏窗体
	之所以用线程是防止阻塞sublime UI
"""
class MyThread(threading.Thread):
	def __init__(self,command,view,output):
		threading.Thread.__init__(self)
		self.command=command
		self.view=view
		self.output=output
		view.m_thread=self
	def run(self):
		startupinfo = subprocess.STARTUPINFO()
		if IS_WIN32:
			startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
			startupinfo.wShowWindow = subprocess.SW_HIDE
			p = self.p = subprocess.Popen(self.command,startupinfo=startupinfo,stderr= subprocess.STDOUT,stdout = subprocess.PIPE)
		else:
			p = self.p = subprocess.Popen(self.command,stderr= subprocess.STDOUT,stdout = subprocess.PIPE)
		returncode = p.poll()
		while returncode is None:
			line = p.stdout.readline()
			returncode = p.poll()
			self.output.run_command("append_content",{"content":line.decode().replace("\r","")})
		lines=p.stdout.readlines();
		for line in lines:
			self.output.run_command("append_content",{"content":line.decode().replace("\r","")})
		delattr(self.view,"m_thread")

"""
	定义我们的run_js命令
	监测是否有上次未执行完毕的子进程
	直接kill掉
	创建输出panel,设置样式与当前js的view样式一样
	显示输出panel,并运行我们的线程
"""
class RunJsCommand(sublime_plugin.TextCommand):
	def run(self, edit):
		if hasattr(self.view,"m_thread"):
			stopThread(self.view)
		filename=self.view.file_name()
		os.chdir(os.path.dirname(filename));
		window = self.view.window()
		output = window.get_output_panel('temp')
		self.output=output
		output.set_read_only(True)
		output.settings().set("color_scheme",self.view.settings().get("color_scheme"))
		window.run_command("show_panel",{"panel": "output.temp","toggle":True})
		MyThread(["node",filename.replace("\\","\\\\")],self.view,output).start()