如何從Sublime Text 2運行Python代碼?

本文翻譯自:How do I run Python code from Sublime Text 2?

I want to set up a complete Python IDE in Sublime Text 2. 我想在Sublime Text 2中設置完整的Python IDE。

I want to know how to run the Python code from within the editor. 我想知道如何從編輯器中運行Python代碼。 Is it done using build system? 使用構建系統完成嗎? How do I do it ? 我該怎麼做 ?


#1樓

參考:https://stackoom.com/question/ZshD/如何從Sublime-Text-運行Python代碼


#2樓

I had the same problem. 我有同樣的問題。 You probably haven't saved the file yet. 您可能尚未保存文件。 Make sure to save your code with .py extension and it should work. 確保使用.py擴展名保存您的代碼,並且該代碼應該可以工作。


#3樓

您可以使用SublimeREPL (首先需要安裝Package Control )。


#4樓

I solved this problem : 我解決了這個問題:

> Preferences –> Browse Packages –> Default 

Open the exec.py file, near line 41-42, the code should look like this : 打開第41-42行附近的exec.py文件,代碼應如下所示:

for k, v in proc_env.iteritems():
    proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())

then delete it or edit it as : 然後將其刪除或編輯爲:

try:    
    for k, v in proc_env.iteritems():
        proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())
except:
    print 'foobar'

#5樓

To RUN press Ctrl B (answer by matiit ) 要運行,請Ctrl B (按matiit回答)

But when Ctrl B does not work , Sublime Text probably can't find the Python Interpreter. 但是,當Ctrl B 不起作用時,Sublime Text可能找不到Python解釋器。 When trying to run your program, see the log and find the reference to Python in path. 嘗試運行程序時,請查看日誌並在路徑中找到對Python的引用。

[cmd:  [u'python', u'-u', u'C:\\scripts\\test.py']]
[path: ...;C:\Python27 32bit;...]

The point is that it tries to run python via command line, the cmd looks like: 關鍵是它試圖通過命令行運行python,cmd如下所示:

python -u C:\scripts\test.py

If you can't run python from cmd, Sublime Text can't too. 如果您無法從cmd運行python,那麼Sublime Text也不會。
(Try it yourself in cmd, type python in it and run it, python commandline should appear) (在cmd中自己嘗試,在其中鍵入python並運行它,應該顯示python命令行)

SOLUTION

You can either change the Sublime Text build formula or the System %PATH% . 您可以更改Sublime Text構建公式或System %PATH%

  • To set your %PATH% : 設置%PATH%
    * You will need to restart your editor to load new %PATH% * 您將需要重新啓動編輯器以加載新的%PATH%

    • Run Command Line* and enter this command: *needs to be run as administrator 運行命令行*,然後輸入以下命令: *需要以管理員身份運行
      SETX /M PATH "%PATH%;<python_folder>"
      for example: SETX /M PATH "%PATH%;C:\\Python27;C:\\Python27\\Scripts" 例如: SETX /M PATH "%PATH%;C:\\Python27;C:\\Python27\\Scripts"

    • OR manually: (preferable) 手動:(首選)
      Add ;C:\\Python27;C:\\Python27\\Scripts at the end of the string. 在字符串末尾添加;C:\\Python27;C:\\Python27\\Scripts 在Win7中設置路徑

  • To set the interpreter's path without messing with System %PATH% see this answer by ppy . 要設置解釋器的路徑而不弄亂System %PATH%請參閱ppy的答案。


#6樓

On Mac OS X, save your file with a .py extension. 在Mac OS X上,以.py擴展名保存文件。 Press + B . + B。 It runs in a window below. 它在下面的窗口中運行。

在此處輸入圖片說明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章