2013-10-01 47 views
0

我做了一个崇高的小脚本,它将从用户计算机上的json文件中提取命令,然后它将打开终端并运行设置/命令。这起作用,除了它没有真正开放终端。它只运行命令(它工作,在我的情况下,它将运行gcc编译一个简单的C文件),并且管道到STDOUT而不打开终端。python 3打开终端并运行程序

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。

回答

1

subprocess.Popen只是用给定的命令创建一个子进程。这与打开终端窗口或任何其他窗口无关。

您必须查看您的平台特定的UI自动化解决方案才能实现您的目标。或者看看Sublime插件机制是否可以做到这一点。

注:

此外,你应该使用os.path.join/os.path.split/os.path.sep等你的路径操作,崇高也运行在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/

+1

感谢您的输入!我会在几个这个尝试,并标记这是否工作。我很欣赏这个带有可变前缀的小小的“nitpick”:) – user1021726

+0

我明白你很欣赏挑剔的大多数人不会:) –

+0

那么如果人们不指出我的错误,我该如何改进呢? :)这是我第一次编写Python,因此会产生错误。 此外,如果有人知道如何打开终端并执行从那里的命令(Windows具体是最高优先级的平台),请回复。 – user1021726