[How to run code by using cmd from sublime text 3 ] - python

I am a newbie in Python, and have a problem. When I code Python using Sublime Text 3 and run directly on it, it does not find some Python library which I already imported. I Googled this problem and found out Sublime Text is just a Text Editor.
I already had code in Sublime Text 3 file, how can I run it without this error?
For example:
'ModuleNotFoundError: No module named 'matplotlib'.
I think it should be run by cmd but I don't know how.

Depending on what OS you are using this is easy. On Windows you can press win + r, then type cmd. This will open up a command prompt. Then, type in pip install matplotlib. This will make sure that your module is installed. Then, navigate to the folder which your code is located in. You can do this by typing in cd Documents if you first need to get to your documents and then for each subsequent folder.
Then, try typing in python and hitting enter. If a python shell opens up then type quit() and then type python filename.py and it will run.
If no python shell opens up then you need to change your environment variables. Press the windows key and pause break at the same time, then click on Advanced system settings. Then press Environment Variables. Then double click on Path. Then press New. Then locate the installation folder of you Python install, which may be in C:\Users\YOURUSERNAME\AppData\Local\Programs\Python\Python36 Now put in the path and press ok. You should now be able to run python from your command line.

Sublime text default build system for python is "Python", which uses the "python" alias.
So if you'd like to use python3 for instance, you have to create a new build system.
Go to Tools > Build system > New build system...
There you have a command to specify, use the binary you'd like to be used by sublimeText, like so :
{
"cmd": ["python3.7", "-u", "$file"]
}
Save the file to python[X].sublime-build, [X] being the version you'd like to use.
Now in your source file, specify the build system to that version of python.
To test that sublime text is using the interpreter you chose, you can use this code :
import sys
print(sys.version_info)
Check this for more informations : https://www.sublimetext.com/docs/3/build_systems.html

Did you try to run it from your terminal once you have writen your script ?
You can also install a Python build system :
- Open sublime and go to tools->build system -> new build system
Save this code in the file:
{
"shell_cmd": "python $file_name<inputf.in>outputf.in",
"selector": "source.python",
"working_dir": "$file_path"
}
save it with any name say “whatEverYourWant”
Now again go to tools -> build system and choose “whatEverYourWant”
Run this using ctrl+shift+B or cmb+P
You can also install "Pycharm" if you are only working with Python. It is an amazing IDE.

Go to tools>build system > new build system
and then copy and paste this code in it
{
"shell_cmd": "start cmd /k python $file_name",
"selector": "source.python",
"working_dir": "$file_path"
}
Save it whatever you like without erasing the extention(.sublime-build)
and then write a python script, go to tools>build system and select the build system you just created.
then run your python script by going to tools>build
or ctrl+b and you will see that your python script will run in the command prompt.
By this way you can get input from the user.
Hope that this helps

Related

Run Python in VSCode in python shell like IDLE

I am well aware of the thread How to execute Python code from within Visual Studio Code
But none of them shows how to get the >>> python shell running with the file imported. Cuz I would like to call functions separately.
I understand that I can get the python shell going by simply typling python in the terminal but the functions in the python file have to manually imported everytime.
Is there a way to run files in VSCode like in IDLE?
you can run the file in an interactive mode in VSC code terminal by using the parameter -i :
python -i py_file.py
Install the Python Extension, then press Ctrl+Shift+P (Command+Shift+P) and type Python: Start REPL. Click the command, and you'll get an interactive Python console.
Assuming you have the official Python extension installed, you can search the command list (Ctrl+Shift+P) for "Python interactive" and you'll see several options that allow to do different variations of this:
Not sure if this was figured out or not, but I was having a similar question. How to simply use something like IDLE (the known '>>>' shell prompt) inside VSCodesee w/o chasing down plugins and their settings? I noticed that no answer was marked confirmed and although insightful, not what I was looking for.
I use Mac and while trying different things to address this, I found that by using/copying the path in the Python Launcher settings I got what I was looking for. Then, I validated the equivalent for Windows. Please see below.
Windows:
If you are using Windows, from your Terminal pane/window in VSCode, enter the path to your python.exe, including the executable name. It is located within the "User > AppData" directory.
For example: C:\Users\YOUR_USER_ID\AppData\Local\Programs\Python\Python310\python.exe
Note that AppData is a hidden folder, so may have to change your view settings in Explorer to show Hidden Items.
MAC:
If you are using MAC, from your Terminal pane/window in VSCode, enter the path to your interpreter
For example: /usr/local/bin/python3
Note: You can also do this directly from a CMD, PowerShell or a Terminal(Mac) window without having to launch IDLE, VSCode or any other coding/scripting app.
To build on the answer already provided, you can automatically run in interactive mode by changing your settings:
Go under File>Preferences>Settings. Search for "arguments" in the search bar. Then under "Python › Terminal: Launch Args", click on the link "Edit in settings.json".
Once settings.json is open, add "-i" with the quotation marks. It should look something like that:
{
"workbench.colorTheme": "Default High Contrast",
"terminal.integrated.localEchoEnabled": "off",
"terminal.integrated.shellIntegration.enabled": false,
"python.terminal.launchArgs": [
"-i"
]
}
Now, it will pass the argument -i every time you run.

How to run pygame inside of visual studio? [duplicate]

Visual Studio Code was recently released and I liked the look of it and the features it offered, so I figured I would give it a go.
I downloaded the application from the downloads page, fired it up, messed around a bit with some of the features ... and then realized I had no idea how to actually execute any of my Python code!
I really like the look and feel/usability/features of Visual Studio Code, but I can't seem to find out how to run my Python code, a real killer because that's what I program primarily in.
Is there is a way to execute Python code in Visual Studio Code?
There is a much easier way to run Python, and it doesn't need any configuration:
Install the Code Runner Extension.
Open the Python code file in Text Editor.
To run Python code:
use shortcut Ctrl + Alt + N
or press F1 and then select/type Run Code,
or right click the Text Editor and then click Run Code in the editor context menu
or click the Run Code button in the editor title menu
or click Run Code button in the context menu of file explorer
To stop the running code:
use shortcut Ctrl + Alt + M
or press F1 and then select/type Stop Code Run
or right click the Output Channel and then click Stop Code Run in the context menu
If you want to add the Python path, you could go to File → Preference → Settings, and add the Python path like below:
"code-runner.executorMap":
{
"python": "\"C:\\Program Files\\Python35\\python.exe\" -u"
}
In case you have installed the Python extension and manually set your interpreter already, you could configure your settings.json file as follows:
{
"python.pythonPath": "C:\\\\python36\\\\python36.exe",
"code-runner.executorMap":
{
"python": "$pythonPath -u $fullFileName"
}
}
Here is how to configure Task Runner in Visual Studio Code to run a .py file.
In your console, press Ctrl + Shift + P (Windows) or Cmd + Shift + P (Apple). This brings up a search box where you search for "Configure Task Runner"
If this is the first time you open the "Task: Configure Task Runner", you need to select "other" at the bottom of the next selection list.
This will bring up the properties which you can then change to suit your preference. In this case you want to change the following properties;
Change the Command property from "tsc" (TypeScript) to "Python"
Change showOutput from "silent" to "Always"
Change args (Arguments) from ["Helloworld.ts"] to ["${file}"] (filename)
Delete the last property problemMatcher
Save the changes made
You can now open your .py file and run it nicely with the shortcut Ctrl + Shift + B (Windows) or Cmd + Shift + B (Apple).
All these answers are obsolete now.
Currently you have to:
install the Python language extension (and Python, obviously)
open folder (important!), open any Python file inside that folder
switch to debug "tab"(?) and click on the gearbox (with hint 'Configure of Fix 'launch.json'')
save the opened launch.json file (it's placed in .vscode subdirectory in the folder opened in step #2)
finally, click the green triangle or hit F5
No additional extensions or manual launch.json editing is required now.
You can add a custom task to do this. Here is a basic custom task for Python.
{
"version": "0.1.0",
"command": "c:\\Python34\\python",
"args": ["app.py"],
"problemMatcher": {
"fileLocation": ["relative", "${workspaceRoot}"],
"pattern": {
"regexp": "^(.*)+s$",
"message": 1
}
}
}
You add this to file tasks.json and press Ctrl + Shift + B to run it.
To extend vlad2135's answer (read his first); that is how you set up Python debugging in Visual Studio Code with Don Jayamanne's great Python extension (which is a pretty full featured IDE for Python these days, and arguably one of Visual Studio Code's best language extensions, IMO).
Basically, when you click the gear icon, it creates a launch.json file in your .vscode directory in your workspace. You can also make this yourself, but it's probably just simpler to let Visual Studio Code do the heavy lifting. Here's an example file:
You'll notice something cool after you generate it. It automatically created a bunch of configurations (most of mine are cut off; just scroll to see them all) with different settings and extra features for different libraries or environments (like Django).
The one you'll probably end up using the most is Python; which is a plain (in my case C)Python debugger and is easiest to work with settings wise.
I'll make a short walkthrough of the JSON attributes for this one, since the others use the pretty much same configuration with only different interpreter paths and one or two different other features there.
name: The name of the configuration. A useful example of why you would change it is if you have two Python configurations which use the same type of config, but different arguments. It's what shows up in the box you see on the top left (my box says "python" since I'm using the default Python configuration).
type: Interpreter type. You generally don't want to change this one.
request: How you want to run your code, and you generally don't want to change this one either. Default value is "launch", but changing it to "attach" allows the debugger to attach to an already running Python process. Instead of changing it, add a configuration of type attach and use that.
stopOnEntry: Python debuggers like to have an invisible break-point when you start the program so you can see the entry-point file and where your first line of active code is. It drives some C#/Java programmers like me insane. false if you don't want it, true otherwise.
pythonPath: The path to your install of Python. The default value gets the extension level default in the user/workspace settings. Change it here if you want to have different Pythons for different debug processes. Change it in workspace settings if you want to change it for all debug processes set to the default configuration in a project. Change it in user setting to change where the extension finds Pythons across all projects. (4/12/2017 The following was fixed in extension version 0.6.1). Ironically enough, this gets auto-generated wrong. It auto-generates to "${config.python.pythonPath}" which is deprecated in the newer Visual Studio Code versions. It might still work, but you should use "${config:python.pythonPath}" instead for your default first python on your path or Visual Studio Code settings. (4/6/2017 Edit: This should be fixed in the next release. The team committed the fix a few days ago.)
program: The initial file that you debugger starts up when you hit run. "${workspaceRoot}" is the root folder you opened up as your workspace (When you go over to the file icon, the base open folder). Another neat trick if you want to get your program running quickly, or you have multiple entry points to your program is to set this to "${file}" which will start debugging at the file you have open and in focus in the moment you hit debug.
cwd: The current working directory folder of the project you're running. Usually you'll just want to leave this "${workspaceRoot}".
debugOptions: Some debugger flags. The ones in the picture are default flags, you can find more flags in the python debugger pages, I'm sure.
args: This isn't actually a default configuration setting, but a useful one nonetheless (and probably what the OP was asking about). These are the command line arguments that you pass in to your program. The debugger passes these in as though they you had typed: python file.py [args] into your terminal; passing each JSON string in the list to the program in order.
You can go here for more information on the Visual Studio Code file variables you can use to configure your debuggers and paths.
You can go here for the extension's own documentation on launch options, with both optional and required attributes.
You can click the Add Configuration button at the bottom right if you don't see the config template already in the file. It'll give you a list to auto generate a configuration for most of the common debug processes out there.
Now, as per vlad's answer, you may add any breakpoints you need as per normal visual debuggers, choose which run configuration you want in the top left dropdown menu and you can tap the green arrow to the left to the configuration name to start your program.
Pro tip: Different people on your team use different IDEs and they probably don't need your configuration files. Visual Studio Code nearly always puts it's IDE files in one place (by design for this purpose; I assume), launch or otherwise so make sure to add directory .vscode/ to your .gitignore if this is your first time generating a Visual Studio Code file (this process will create the folder in your workspace if you don't have it already)!
There is a Run Python File in Terminal command available in the Python for Visual Studio Code extension.
As stated in Visual Studio Code documentation, just right-click anywhere in the editor and select Run Python File in Terminal.
Install the Python extension (Python should be installed in your system). To install the Python Extension, press Ctrl + Shift + X and then type 'python' and enter. Install the extension.
Open the file containing Python code. Yes! A .py file.
Now to run the .py code, simply right click on the editor screen and hit 'Run Python File in the Terminal'. That's it!
Now this is the additional step. Actually I got irritated by clicking again and again, so I set up the keyboard shortcut.
Hit that Settings-type-looking-like icon on bottom-left side → Keyboard Shortcuts → type 'Run Python File in the Terminal'. Now you will see that + sign, go choose your shortcut. You're done!
So there are four ways to run Python in Visual Studio Code so far:
Via an integrated terminal (come on, it's integrated! So technically you run it from within Visual Studio Code ;)
No need to install any extension.
No need to create and configure anything (assuming that you already have python in your $PATH).
⌃Space (open terminal) and python my_file.py (run file).
Via custom Task (accepted Fenton's answer):
No need to install any extension.
Default Visual Studio Code's way of doing things.
Beware not to copy-paste the answer because its problemMatcher.pattern.regexp is broken and it hangs the editor. It's better to either delete problemMatcher or change the regexp to at least ^\\s+(.*)$.
Via Code Runner extension (#JanHan's answer):
Need to configure code-runner.executorMap in User Settings (add path to your python).
Very helpful extension especially if you run not only Python in Visual Studio Code.
Via Microsoft's official Python extension (vlad2135's answer):
Need to create launch.js (a couple of clicks in Visual Studio Code's Debug tab).
The extension is a must-have for those who wants to use Visual Studio Code as a primary IDE for Python.
There is a lot of confusion around Visual Studio Code tasks and the debugger. Let's discuss about it first so that we understand when to use tasks and when to use the debugger.
Tasks
The official documentation says -
Lots of tools exist to automate tasks like linting, building,
packaging, testing, or deploying software systems. Examples include
the TypeScript Compiler, linters like ESLint and TSLint as well as
build systems like Make, Ant, Gulp, Jake, Rake, and MSBuild.
.... Tasks in VS Code can be configured to run scripts and start
processes so that many of these existing tools can be used from within
VS Code without having to enter a command line or write new code.
So, tasks are not for debugging, compiling or executing our programs.
Debugger
If we check the debugger documentation, we will find there is something called run mode. It says -
In addition to debugging a program, VS Code supports running the
program. The Debug: Start Without Debugging action is triggered with
Ctrl+F5 and uses the currently selected launch configuration. Many of
the launch configuration attributes are supported in 'Run' mode. VS
Code maintains a debug session while the program is running, and
pressing the Stop button terminates the program.
So, press F5 and Visual Studio Code will try to debug your currently active file.
Press Ctrl + F5 and Visual Studio Code will ignore your breakpoints and run the code.
Configuring the debugger
To configure the debugger, go through the documentation. In summary it says, you should modify the launch.json file. For starters, to run the code in integrated terminal (inside Visual Studio Code), use -
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
To run the code in an external terminal (outside of Visual Studio Code), use -
{
"name": "Python: Current File (External Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "externalTerminal"
}
N.B. If all documentation was easy to search and understand then we probably would not need Stack Overflow. Fortunately, the documentation I mentioned in this post is really easy to understand. Please feel free to read, ponder and enjoy.
In the latest version (1.36) of Visual Studio Code (Python):
Press F5 and then hit Enter to run your code in the integrated terminal.
Ctrl + A and then hit Shift + Enter to run your code in the interactive IPython shell.
You no longer need any additional extensions. You can simply switch the output of the debugger to the integrated terminal.
Ctrl+Shift+D, then select Integrated Terminal/Console from the dropdown at the top.
If I just want to run the Python file in the terminal, I'll make a keyboard shortcut for the command because there isn't one by default (you need to have the Python interpreter executable in your path):
Go to Preferences (the gear icon on the bottom left) → Keyboard Shortcuts
Type 'run Python file in terminal'
Click on the '+' for that command and enter your keyboard shortcut
I use Ctrl + Alt + N.
If you are using the latest version of Visual Studio Code (version 1.21.1). The task.json format has changed, see here. So the answer by Fenton and by python_starter may no longer be valid.
Before starting configuration
Before you start configuring Visual Studio Code for running your Python file.
Make sure that you have installed Python and added its executable to your system PATH.
You must set the folder where your python source file resides as your working folder (go to File -> Open Folder to set your working folder).
Configuration steps
Now you can configure the task. The following steps will help you run your python file correctly:
use Ctrl+Shift+P and input task, you will see a list of options, select Tasks: Configure Task.
You will then be prompted create task.json from template, choose this option, and you will be prompted to choose from a list of options. Choose Others.
Then in the opened task.json file, use the following settings:
{
"version": "2.0.0",
"tasks": [
{
"label": "run this script",
"type": "shell",
"command": "python",
"args": [
"${file}"
],
"problemMatcher": []
}
]
}
In the above settings, you can give a meaningful label to this task. For example, run python.
Go to the Tasks menu and click Run Task. You will be prompted to choose the task. Just choose the newly created run this script task. You will see the result in the TERMINAL tab.
For a more complete tutorial about task configuration, go to the Visual Studio Code official documentation.
Here's the current (September 2018) extensions for running Python code:
Official Python extension: This is a must install.
Code Runner: Incredibly useful for all sorts of languages, not just Python. I would highly recommend installing.
AREPL: Real-time Python scratchpad that displays your variables in a side window. I'm the creator of this, so obviously I think it's great, but I can't give a unbiased opinion ¯\(ツ)/¯
Wolf: Real-time Python scratchpad that displays results inline
And of course if you use the integrated terminal you can run Python code in there and not have to install any extensions.
Super simple:
Press the F5 key and the code will run.
If a breakpoint is set, pressing F5 will stop at the breakpoint and run the code in debug mode.
Other Method - To add Shortcut
Note: You must have Python Extension By Microsoft installed in Visual Studio Code, and the Python interpreter selected in the lower-left corner.
Go to File → Preferences → Keyboard Shortcuts (alternatively, you can press Ctrl + K + S)
In the search box, enter python.execInTerminal
Double click that result (alternatively, you can click the plus icon)
Press Ctrl + Alt + B to register this as the keybinding (alternatively, you can enter your own keybinding)
Now you can close the Keyboard Shortcuts tab
Go to the Python file you want to run and press Ctrl + Alt + B (alternatively, you can press the keybinding you set) to run it. The output will be shown in the bottom terminal tab.
in new Version of VSCode (2019 and newer) We have run and debug Button for python,
Debug :F5
Run without Debug :Ctrl + F5
So you can change it by go to File > Preferences > Keyboard Shortcuts
search for RUN: start Without Debugging and change Shortcut to what you want.
its so easy and work for Me (my VSCode Version is 1.51 but new update is available).
Note: You must have Python Extension By Microsoft installed in Visual Studio Code, and the Python interpreter selected in the lower-left corner.
Go to File → Preferences → Keyboard Shortcuts (alternatively, you can press Ctrl + K + S)
In the search box, enter python.execInTerminal
Double click that result (alternatively, you can click the plus icon)
Press Ctrl + Alt + B to register this as the keybinding (alternatively, you can enter your own keybinding)
Now you can close the Keyboard Shortcuts tab
Go to the Python file you want to run and press Ctrl + Alt + B (alternatively, you can press the keybinding you set) to run it. The output will be shown in the bottom terminal tab.
Press F5 to run with Debugging
Press Ctrl+F5 to run with Debugging ignoring breakpoints.
Running the current python file as is does not have a keybinding associated by default, but you can set this with:
Ctrl+Shift+P
Type "Run Python file in Terminal"
Hover over it and click the ⚙️ icon
Double click "Keybinding"
Set your desired shortcut
I had installed Python via Anaconda.
By starting Visual Studio Code via Anaconda I was able to run Python programs.
However, I couldn't find any shortcut way (hotkey) to directly run .py files.
(Using the latest version as of Feb 21st 2019 with the Python extension which came with Visual Studio Code.
Link: Python extension for Visual Studio Code)
The following worked:
Right clicking and selecting 'Run Python File in Terminal' worked for me.
Ctrl + A then Shift + Enter (on Windows)
The below is similar to what #jdhao did.
This is what I did to get the hotkey:
Ctrl + Shift + B // Run build task
It gives an option to configure
I clicked on it to get more options. I clicked on Other config
A 'tasks.json' file opened
I made the code look like this:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Run Python File", //this is the label I gave
"type": "shell",
"command": "python",
"args": ["${file}"]
After saving it, the file changed to this:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Run Python File",
"type": "shell",
"command": "python",
"args": [
"${file}"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
After saving the file 'tasks.json', go to your Python code and press
Ctrl + Shift + B.
Then click on Run task → Run Python File // This is the label that
you gave.
Now every time that you press Ctrl + Shift + B, the Python file will automatically run and show you the output :)
There is an easiest way to make a shortcut for run in terminal command:
Click on the settings icon on the left bar.
Then click on Keyboard Shortcuts.
Paste python.execInTerminal in search bar on top.
Now double-click on the Keybinding column opposite the Python: Run Python File in Terminal command and set the shortcut.
I use Python 3.7 (32 bit). To run a program in Visual Studio Code, I right-click on the program and select "Run Current File in Python Interactive Window". If you do not have Jupyter, you may be asked to install it.
A simple and direct Python extension would save both time and efforts.
Linting, debugging, code completion are the available features once installation is done. After this, to run the code proper Python installation path needs to be configured in order to run the code. General settings are available in User scope and Workspace can be configured for Python language– "python.pythonPath": "c:/python27/python.exe"
With above steps at least the basic Python programs can be executed.
If you are running code and want to take input via running your program in the terminal, the best thing to do is to run it in terminal directly by just right click and choose "Run Python File in Terminal".
From Extensions, install Code Runner. After that you can use the shortcuts to run your source code in Visual Studio Code.
First: To run code:
use shortcut Ctrl + Alt + N
or press F1 and then select/type Run Code,
or right click in a text editor window and then click Run Code in the editor context menu
or click the Run Code button in editor title menu (triangle to the right)
or click Run Code in context menu of file explorer.
Second: To stop the running code:
use shortcut Ctrl + Alt + M
or press F1 and then select/type Stop Code Run
or right click the Output Channel and then click Stop Code Run in the context menu
If you install Python language extension for VSCode, it also installs Jupyter and Pylance by default, which lets you run Python code in interactive manner.
All you have to do is use # %% before the code that you want to execute interactively.
As soon as you insert # %%, you can see that VSCode creates a new Jupyter Cell for you.
And from there you can click on the Run Cell cell menu and you can see the result.
So, all you have to do is type the following code in your VSCode,
# %%
text = 'Hello World from inline interactive Python'
print(text)
To run python3 on windows vs code:
Download the python interpreter from their official site
Install the python packages for vs code. This can be installed directly from vscode's extension manager
Verify that your python3 has been installed by running this command:
py -3 --version
Run your script with the following command from vscode's terminal:
py -3 main.py
For more information, head over here for details installation procedure.
In order to launch the current file with the respective venv, I added this to file launch.json:
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"pythonPath": "${workspaceFolder}/FOO/DIR/venv/bin/python3"
},
In the bin folder resides the source .../venv/bin/activate script which is regularly sourced when running from a regular terminal.
If you have a project consisting of multiple Python files and you want to start running/debugging with the main program independent of which file is current you create the following launch configuration (change MyMain.py to your main file).
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Main File",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/MyMain.py",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}"
}
]
}
I used my existing anaconda environment to run python. rather than using the python user appdata\local\programs\python use the anaconda install python by environment. This will give you access to all your libraries in the environment.
1. View->Command Palette->Open user settings
2. search python
a. Python: default interpreter path = c:\users\yourname\Anaconda3\python.exe
b. save the file
3. View->Command Palette->python:select interpreter
a. arrow down to your workspace name
b. select your python and environment
create a python script and run it.
see https://code.visualstudio.com/docs/python/environments

SublimeREPL 3 python is always closed

I am learning Python and i am using Sublime Text 3 as a Python's editor.
But now i have a little problem. I am trying to use SublimeRepl and i've watched so many tutorials how to use it, but when i have try to open python project with REPL it says me "repl closed". It always says that. Repl>Python works normally, but when i try to open something with it, it is always closed.
I also have made changes to main.sublime-menu like adding "-i" and replacing python (after cmd) with pythons path.
Also trying to reinstall sublime didn't help.
I tried running Python files on this code:
age = input("How old are you: ")
print(age)
That's it :). Thank's for any support.
I am using Python 3.6
Can you indicate what version of Python you are using? There have been issues that are related to the version.
Another suggestion is located here.
Go to ..\Roaming\Sublime Text 3\Packages\SublimeREPL\config\Python directory.
Edit Main.sublime-menu file
Search for cmd": ["python", "-u", "$file_basename"] and replace it with cmd": ["python", "-u", "-i", "$file_basename"]. Value "-i" will make your python interactive.
Before doing those steps, to force sublime text build your python code in an interactive python shell, follow the steps below:
Go to ..\Roaming\Sublime Text 3\Packages\User directory.
Create a new file named SublimeREPL-python.sublime-build
Copy this contain into it and save it:
{
"target": "run_existing_window_command",
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
Open sublime text, Go to: Tools > Build system and select: SublimeREPL-python.sublime-build instead of Automatic

How to setup Atom's script to run Python 3.x scripts? May the combination with Windows 7 Pro x64 be the issue?

I'm trying to switch from Notepad++ to Atom, but I just can't manage to get my scripts executed in Atom.
I followed this answer (so I already installed script) which is not really extensive and also the rest on the web doesn't offer anything comprehensible for beginners.
In Notepad++ NPPexec I used to
NPP_SAVE
cd "$(FULL_CURRENT_PATH)"
C:\Python34\python.exe -u "$(FULL_CURRENT_PATH)"
and in Sublime Text 2 I made it run by creating a new "Build System":
{
"cmd": ["C:\\python34\\python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
Can you please guide me how to setup Atom to be able to execute Python scripts with Python 3.4 scripts with a keyboard short-cut?
I already tried to set my init-script to:
process.env.path = ["C:\Python34\python.exe",process.env.PATH].join(";")
respectively
process.env.path = ["C:\Python34",process.env.PATH].join(";")
with no success.
When I go to Packages -> Script -> Configure Script and type
C:\\Python34\\python.exe
it works. But thats not a permanent solution.
When I press Ctrl+Shift+B to run a script, without configuring it before (as it is supposed to work), I get (suggestion of ig0774's comment implemented):
(it doesn't matter whether it is C:\Python34 or C:\Python34\)
It complains that python is not in my path - but it is.
I read multiple times that Windows 7/8 64bit together with Python 3.x could cause issues with certain packages. May this be the reason in ths case as well? I have Windows 7 Pro x64.
Update
As I've switched to VSCode and probably stay there, I'm not willing/don't have the time to try out all the answers, so I let the community judge the answers and accept always the highest voted. Please ping me, if it's not correct anymore.
This can be easily solved by editing the /home/.atom/packages/script/lib/grammars.coffee file (note that the atom folder is hidden so you might have to press ctrl+H to view hidden files and folders)
Inside grammars.coffee find:
Python:
"Selection Based":
command: "python"
args: (context) -> ['-u', '-c', context.getCode()]
"File Based":
command: "python"
args: (context) -> ['-u', context.filepath]
and replace with:
Python:
"Selection Based":
command: "python3"
args: (context) -> ['-u', '-c', context.getCode()]
"File Based":
command: "python3"
args: (context) -> ['-u', context.filepath]
Save changes, restart Atom and enjoy running your scripts with python 3
EDIT: On Windows I believe the grammars.coffee file is located in
C:/Users/Your_Username/AppData/Local/atom/packages
Again, the AppData folder is hidden so you might have to change your settings to view hidden files and folders.
To expand on #matt-nona answer. You can go to his mentioned config file right from Atom. Simply go to settings then "Open Config Folder":
Then /packages/script/lib/grammars.coffee Find "Python" and make the appropriate change to python3:
Following up on Matt Nona's advice , when Atom starts-> Welcome Guide (or control+shift+T)-> 5th one down 'Hack on the Init Script'. A blank page will open and you can add that modifications in there.
Update: for any other souls looking for this answer - On my Mac I do not have a grammars.coffee file within atom script config file.
Instead, there s a grammars folder, and I have a python.coffee file in there. The same changes outlines in the screenshot (ie add '3' to the end of the two mentions of python) fixed my issue and atom automatically runs Python3 now.
Not sure if the above answers are Windows specific or if there have been dev changes since 2017.
same problem just like you. 'Packages -> Script -> Configure Script' is not permanent. So I has tryed another script runner:https://atom.io/packages/atom-runner, just found the problem is in the python script itself.
When I use atom-runner, I got error message like this:
atom-runner error
So it remind me that in the beginning of the python script: ' #!/usr/bin/env python3 '
It's obvious that the ENV_PATH is WRONG here. I should revise it in my python script.
Setting the PATH within Atom did not work, setting it with the cmd, via
set PATH=%PATH%;C:\Python34
neither, and setting it in the Windows 7 system properties failed as well.
However reinstalling Python 3.4 and check Add python.exe to Path
seems to be neccesary. Also I needed to uninstall Atom completely (inculding all packages or a least script) and reinstall it from scratch.
After all these steps:
Install Python with Add to Path
Install Atom
Install script package
it works out of the box (Ctrl+Shift+B) and no further steps are required.
I still don't know what was the reason before and I don't know which of this steps are really required. So feel free to include your procedure without reinstalling everything.
Update
Reinstalling everything is certainly not necessary, simply updating/repairing the installation with the installer is sufficient.
Use the script-runner https://atom.io/packages/script-runner/
"N.B. these keyboard shortcuts are currently being reviewed, input is welcome.
Command Mac OS X Linux/Windows
Run: Script ctrl-x alt-x
Run: Terminate ctrl-c alt-c"
And "Run Terminate" (Alt + c) to use the current python in your system.
edit your python.coffee script
$ sudo nano .atom/packages/script/lib/grammars/python.coffee
For Linux and Mac, adding environment in the script will pick correct python version. (command + I to run)
for running with python3
#!/usr/bin/env python3

Sublime Text 3 - Python Build System Confusion

First, thanks in advance for any assistance.
I'm diving into Python and would like to continue to use Sublime Text 3 as I do for other projects. As I understand it, the internal version of Python is 3.3, but I'd like to use 2.7.6. Following other examples, I created a new build system as follows:
{
"cmd": ["/usr/local/bin/python", "-u", "$file"],
"file_regex": '^[ ]*File \"(...*?)\', line ([0-9]*)",
"selector": "source.python"
}
When I switch to this new build, open the Console and then try to run the following command in the Python 2 syntax
print "Hello, world."
I get an "invalid syntax" error. However, if I try to run the same command in parentheses as required for Python 3
print("Hello, world.")
the command executes successfully. In other words, it does not appear that the Console is using the 2.7.6 build system.
What I find confusing is that if I save a new test.py file using the same Python 2 syntax as above, build it using the default Python 3 build system the Console outputs a successful execution of the print command – even though the syntax should not be compatible (as occurs in the Console). It seems I get different results running commands directly in the Console and running a build of file.
I'm sure this can be chalked up to a misunderstanding on my part, but I'd appreciate any thoughts.
Cheers.
So, one thing you may not be aware of is that
print("Hello World")
is valid in both Python 3 and later revisions of Python 2, including 2.7.6, so if you're running your file from the command line, it'll execute properly regardless of which interpreter you're using.
You may also be confusing yourself regarding the Console in Sublime and the build systems. The Console, opened by hitting Ctrl` or selecting View -> Show Console, is running Sublime's internal version of Python, a stripped-down Python 3.3.3 if you're using the latest build. You cannot run Py2 commands in the console, no matter how hard you try. It is useful for running Python API commands to control Sublime itself, but it's of no use in building non-plugin files.
Build Systems let you run your programs through external compilers, interpreters, processors, or what have you. They are activated by choosing one in the Tools -> Build System menu, and then hitting CtrlB (or CommandB on OS X) to run it.
So, to verify that your build systems are working as desired, create a new .py file with
print "Hello World"
in it. Save the file, and select Tools -> Build System -> Python (the first one in the menu, between Make and Ruby). Hit CtrlB or CommandB as appropriate for your OS, and check out the pane that opens at the bottom of Sublime. It should show "Hello World" at the top line, then another line saying [Finished in 0.05 seconds] or something similar underneath it.
Now, select Tools -> Build System -> Python 3 (or whatever you named your new build system) and hit Ctrl/CommandB, and you should now see a traceback in the build pane for invalid syntax.

Categories