我在sublime中创建了一个小脚本,它将从用户计算机上的json文件中提取命令,然后它将打开终端并运行settings /命令。这是有效的,除了它没有真正打开终端。它只运行命令(它可以工作,因为在我的情况下它将运行gcc来编译一个简单的C文件),并在不打开终端的情况下通过STDOUT管道。
import json
import subprocess
import sublime_plugin
class CompilerCommand(sublime_plugin.TextCommand):
def get_dir(self, fullpath):
path = fullpath.split("\\")
path.pop()
path = "\\".join(path)
return path
def get_settings(self, path):
_settings_path = path + "\\compiler_settings.json"
return json.loads(open(_settings_path).read())
def run(self, edit):
_path = self.get_dir(self.view.file_name())
_settings = self.get_settings(_path)
_driver = _path.split("\\")[0]
_command = _driver + " && cd " + _path + " && " + _settings["compile"] + " && " + _settings["exec"]
proc = subprocess.Popen(_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
我不确定使用subprocess.Popen
是否是正确的方法,因为我是Python的新手。
所以要重新迭代;我希望它打开终端,运行命令,并让终端保持打开,直到用户按下ENTER或其他东西。如果重要的话,我正在运行Windows 7和Python 3。
答案 0 :(得分:1)
subprocess.Popen
只是使用给定的命令创建一个子进程。这与打开终端窗口或任何其他窗口无关。
您必须查看特定于平台的UI自动化解决方案才能实现您的目标。或者看看Sublime插件机制是否可以做到这一点。
备注:强>
此外,您应该使用os.path.join
/ os.path.split
/ os.path.sep
等进行路径操作 - 例如,Sublime也在OS X上运行,而OS X不使用反斜杠。此外,需要关闭文件句柄,因此请使用:
with open(...) as f:
return json.load(f) # also not that there is no nead to f.read()+json.loads()
# if you can just json.load() on the file handle
此外,字符串通常应使用字符串插值构建:
_command = "{} && cd {} && {} && {}".format(_driver, _path, _settings["compile"], _settings["exec"])
...而且,你不应该用_
为你的局部变量添加前缀 - 它看起来不太好并且在Python中没有用处;当我们参与其中时,我不妨利用这个机会建议你阅读PEP8:http://www.python.org/dev/peps/pep-0008/。