简体   繁体   English

如何从 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 ?我该怎么做 ?

Tools -> Build System -> (choose) Python then:工具 -> 构建系统 ->(选择)Python 然后:

To Run:跑步:

      Tools -> Build

      -or-

      Ctrl + B

      CMD + B  (OSX)

This would start your file in the console which should be at the bottom of the editor.这将在应该位于编辑器底部的控制台中启动您的文件。

To Stop:停止:

       Ctrl + Break or Tools -> Cancel Build

       Fn + C (OSX)

You can find out where your Break key is here: http://en.wikipedia.org/wiki/Break_key .您可以在此处找到Break密钥的位置: http : //en.wikipedia.org/wiki/Break_key

Note: CTRL + C will NOT work.注: CTRL + C无法工作。

What to do when Ctrl + Break does not work:Ctrl + Break不起作用时怎么办:

Go to:去:

Preferences -> Key Bindings - User首选项 -> 键绑定 - 用户

and paste the line below:并粘贴以下行:

{"keys": ["ctrl+shift+c"], "command": "exec", "args": {"kill": true} } 

Now, you can use ctrl+shift+c instead of CTRL+BREAK现在,您可以使用ctrl+shift+c代替CTRL+BREAK

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

在此处输入图片说明

Edit %APPDATA%\\Sublime Text 2\\Python\\Python.sublime-build编辑 %APPDATA%\\Sublime Text 2\\Python\\Python.sublime-build

Change content to:将内容更改为:

{
    "cmd": ["C:\\python27\\python.exe", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

change the "c:\\python27" part to any version of python you have in your system.将“c:\\python27”部分更改为您系统中的任何版本的python。

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\\ScriptsWin7设置路径

  • To set the interpreter's path without messing with System %PATH% see this answer by ppy .要设置解释器的路径而不与 System %PATH%混淆,请参阅ppy 的此答案。

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

If using python 3.x you need to edit the Python3.sublime-build如果使用 python 3.x 你需要编辑Python3.sublime-build

(Preferences > Browse packages > Python 3) (首选项 > 浏览包 > Python 3)

to look like this:看起来像这样:

{
  "path": "/usr/local/bin",
  "cmd": ["python3", "-u", "$file"],
  "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  "selector": "source.python"
}

[ This applies to ST3 (Win), not sure about ST2 ] [这适用于ST3(Win),不确定ST2]

To have the output visible in Sublime as another file (+ one for errors), do this:要将 Sublime 中的输出作为另一个文件(+ 一个错误)可见,请执行以下操作:

  1. Create a new build system: Tools > Build Systems > New Build System...创建一个新的构建系统: Tools > Build Systems > New Build System...
  2. Use the following configuration:使用以下配置:
{
        "cmd": ["python.exe", "$file", "1>", "$file_name.__STDOUT__.txt", "2>", "$file_name.__STDERR__.txt"],
        "selector": "source.python",
        "shell": true,
        "working_dir": "$file_dir"
    }
  1. For your Python file select the above build system configuration file: Tools > Build Systems > {your_new_build_system_filename}对于您的 Python 文件,选择上述构建系统配置文件: Tools > Build Systems > {your_new_build_system_filename}
  2. ctrl + b ctrl + b
  3. Now, next to your file, eg "file.py" you'll have "file.__STDOUT__.py" and "file.__STDERR__.py" (for errors, if any)现在,在您的文件旁边,例如"file.py"您将拥有"file.__STDOUT__.py""file.__STDERR__.py" (对于错误,如果有的话)
  4. If you split your window into 3 columns, or a grid, you'll see the result immediately, without a need to switch panels / windows如果您将窗口拆分为 3 列或网格,您将立即看到结果,无需切换面板/窗口

In python v3.x you should go to : Tools->Build System->New Build System .在 python v3.x 中,您应该转到: Tools->Build System->New Build System

Then, it pop up the untitled.sublime-build window in sublime text editor.Enter setting as:然后,它在 sublime 文本编辑器中弹出 untitled.sublime-build 窗口。输入设置为:

{

    "cmd": ["path_to_the_python.exe","-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

To see the path, Type following in terminal as :要查看路径,请Type following in terminal as

python
>>> import sys
>>>print(sys.executable)

You can make more than one Build System but it should default save inside Packages of Sublime text with .sublime-build extension.您可以制作多个构建系统,但它应该默认保存在带有.sublime-build扩展名的 Sublime 文本包中

Then, select the new Build System and press cltr+b or other based on your os.然后,选择新的构建系统并根据您的操作系统按cltr+b或其他。

Cool U guys, I just found this:酷你们,我刚刚发现这个:

http://ptomato.wordpress.com/2012/02/09/geek-tip-running-python-guis-in-sublime-text-2/ http://ptomato.wordpress.com/2012/02/09/geek-tip-running-python-guis-in-sublime-text-2/

It explains (like one of the answers above) how to edit this exec.py in the default directory.它解释了(如上面的答案之一)如何在默认目录中编辑此exec.py。

I had the problem that my PYTHON UI APPLICATION would not start.我遇到了PYTHON UI 应用程序无法启动的问题。 I commented out the last line from the following snipped:我从以下片段中注释掉了最后一行:

    # Hide the console window on Windows
    startupinfo = None
    if os.name == "nt":
        startupinfo = subprocess.STARTUPINFO()
        #startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

and, taaadaaaa, I could start my app by pressing Ctrl+B.而且,taaadaaaa,我可以通过按 Ctrl+B 来启动我的应用程序。 Funny line anyways, uh?反正很有趣,嗯? And a big thank you to whoever wrote that article ;-)非常感谢写那篇文章的人;-)

I solved this problem :我解决了这个问题:

> Preferences –> Browse Packages –> Default 

Open the exec.py file, near line 41-42, the code should look like this :打开exec.py文件,靠近第 41-42 行,代码应如下所示:

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'

I ran into the same problem today.我今天遇到了同样的问题。 And here is how I managed to run python code in Sublime Text 3:这是我如何在 Sublime Text 3 中运行 python 代码:

  1. Press Ctrl + B (for Mac, + B ) to start build system.Ctrl + B (对于 Mac, + B )开始构建系统。 It should execute the file now.它现在应该执行该文件。
  2. Follow this answer to understand how to customise build system.按照此答案了解如何自定义构建系统。

What you need to do next is replace the content in Python.sublime-build to接下来需要做的是将Python.sublime-build的内容替换为

{
    "cmd": ["/usr/local/bin/python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
}

You can of course further customise it to something that works for you.您当然可以进一步将其自定义为适合您的内容。

seems the Ctrl+Break doesn't work on me, neither the Preference - User...似乎 Ctrl+Break 对我不起作用,首选项 - 用户...

use keys, Alt → t → c使用快捷键 Alt → t → c

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 扩展名保存您的代码,它应该可以工作。

One thing to note about the aforementioned build system : you can write (and use) custom .sublime-build files or even per project build_systems clause (in your project settings).关于上述构建系统需要注意的一件事:您可以编写(和使用)自定义.sublime-build文件,甚至每个项目的build_systems子句(在您的项目设置中)。 This allows you to do useful things like a fancy test runner with ANSI colors output .这允许你做一些有用的事情,比如一个带有 ANSI 颜色输出的花哨的测试运行器

For even more "full IDE" features, you can use the excellent SublimePythonIDE package:对于更多“完整的 IDE”功能,您可以使用优秀的SublimePythonIDE包:

  • code completion (intel)代码完成(英特尔)
  • jump to definition & object description跳转到定义和对象描述
  • proper linting/pep8适当的掉毛/pep8
  • supports different interpreters with virtualenv使用 virtualenv 支持不同的解释器

Disclosure: I've contributed a PR to that package, and I use it all the time, but there are others .披露:我已经贡献了PR该程序包,我用它所有的时间,但其他人

Use a real python console alongside Sublime与 Sublime 一起使用真正的 python 控制台

Both Sublime's build system and SublimeREPL (the answers above) are limited in that you can't easily interact with the workspace variables after you run your file. Sublime 的构建系统和 SublimeREPL(上面的答案)都受到限制,因为您在运行文件后无法轻松与工作区变量进行交互。

If you want to run a script, then work in a REPL-like fashion (like you would in an IDE), then I recommend having Sublime open alongside an IPython console.如果你想运行一个脚本,然后以类似 REPL 的方式工作(就像你在 IDE 中一样),那么我建议在 IPython 控制台旁边打开 Sublime。 Using AutoHotKey (Windows) or AutoKey (Linux), you can set this up such that a single shortcut will copy the filename (or just the selected code) and then paste this in the console to run the file.使用 AutoHotKey (Windows) 或 AutoKey (Linux),您可以将其设置为单个快捷方式将复制文件名(或仅复制选定的代码),然后将其粘贴到控制台中以运行文件。

Detailed instructions for Linux or Windows LinuxWindows 的详细说明

您可以通过“查看/显示控制台”或Ctrl + `访问 Python 控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM