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.
Related
For some weird reason, Visual Studio hasn't performed correctly what I've been doing in python. Unlike all the tutorials I find, where they normally run in the "output" field, in mine it displays correctly only in the terminal.
print('test','trying', sep='#')
Output:
File "/Users/x/Desktop/Livre.py", line 2
print('test','trying', sep='#')
^
SyntaxError: invalid syntax
Terminal:
test#trying
Here is an example of the SEP command, but the same thing happens, for example, when I put special characters in lists, even when I use utf8.
Does anyone have an idea why this is happening?
EDIT:
So, I understood what is happening, like was told in one of the answers: Visual Studio Code is using python version 2.7 in the "Output" field, for some reason, even though I have installed and reinstalled Code Runner and Python 3.10 several times.
Unfortunately so far it hasn't solved the problem.
But I haven't given up yet, and somewhere here in Stack I wiil discover how to figure it out :)
Install and run the code with Code Runner.
After installing this extension, the triangular play button in the upper right corner will have three options
Select Run Code to run the code, and the result will be output in the OUTPUT panel.
Right-clicking directly on the editor interface and selecting Run Code is the same.
Tips:
Among the three options, Run Code is provided by Code Runner, and the other Run Python File and Debug Python File are provided by Microsoft's official extension python.
I have a struggle using this editor. I tried it a year ago and after some hair-pulling, ended up leaving it for another platform. I came back today, and I want to fix my problem and go farther than just step one.
I got a picture of my code and will provide the code written out here as well. I will also be providing a picture of the book I am using (Python Crash Course 2nd Edition) with the instructions given to me.
If any more info is needed, or some clarification. Please let me know. I want to get moving past this obstacle.
Picture of my code
print("Hello Python World!")
[WinError 2] The system cannot find the file specified
[cmd: ['python3', '-u', 'C:\\Users\\2\\Desktop\\New folder\\Coding\\python\\python_work\\hello_world.py']]
[dir: C:\Users\2\Desktop\New folder\Coding\python\python_work]
[path: C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\2\Desktop\Python\Python310;C:\Users\2\Desktop\Python\Python310\Scripts;C:\Users\2\AppData\Local\Programs\Python\Python310\Scripts\;C:\Users\2\AppData\Local\Programs\Python\Python310\;C:\Users\2\AppData\Local\Microsoft\WindowsApps;;C:\Program Files\JetBrains\PyCharm Community Edition 2021.3.1\bin;]
[Finished]
Picture of Directions from Book (pg 10)
{
"cmd": ["python3", "-u", "$file"],
}
print("Hello Python World!")
Hello Python World!
[Finished in 0.1s]
Once again, if any clarification or extra detail is needed, just let me know and I will clarify to the best of my ability.
Problem solved
Ended up switching the build system from Python3 to Python and removed the cmd directions from the book. Problem fixed. Big thanks!
The instructions in your book are either out of date or flat out misleading you; I would not recommend following them.
You only need to create your own sublime-build file to execute a Python program as Python version 3 if you're running Sublime Text 3 AND you are on Linux/MacOS.
The Python.sublime-build file that ships with ST3 will execute python.exe by default on Windows which (if you have Python installed and on the PATH) will work. The version of the file that ships with ST4 executes the py.exe helper on Windows, which is always available on the PATH and will find the right version of Python for you no matter where it's installed (so long as it is in fact installed).
Using the name python3 is required only on Linux and MacOS, for which the name python refers to Python 2 and not Python 3 (and it does not exist on Windows at all, which is the ultimate source of your problem). In ST3 the build always tries to execute python on these platforms, but in ST4 the default is now python3.
The build as outlined in the book doesn't set up an appropriate selector to allow the build to be auto selected or a file_regex to match errors to allow for error navigation. Perhaps later parts of the book include that; the built in build supports it directly out of the box.
In any case, the most expedient way to test out your code would be to select Python under Tools > Build Systems and then run the build again. Sublime is going to ask you if you want the Python or the Python - Syntax Check build; choose the first one in the list.
The Syntax Check variant only compiles your code but doesn't actually run it, which is almost never want you want.
If that works, you can delete your sublime-build file and change the selected build to Automatic, which will cause Sublime to pick the Python build for you automatically so long as you execute the build while you're editing a Python file.
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
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
I am trying to use Curses in PyDev in Eclipse in Win7.
I have installed Python 3.2 (64bit) and curses-2.2.win-amd64-py3.2. When I input the following testing codes into PyDev:
import curses
myscreen = curses.initscr()
myscreen.border(0)
myscreen.addstr(12, 25, "Python curses in action!")
myscreen.refresh()
myscreen.getch()
curses.endwin()
It did not show any syntax error, so I think the curses was installed correctly.
However, when I ran it as Python Run, the output showed: Redirection is not supported. I do not know where this problem comes from. I googled a lot but can't find related information.
Recent PyCharm versions (I am currently running 2017.2, not sure when this option was added, or if it has been there the entire time) have the option "Emulate terminal in output console". Curses works with this option checked.
You cannot expect to use curses with a non-terminal.
Probably you get this because you are running the script from inside an IDE, like PyCharm or any other.
All IDEs do provide consoles that are not terminals, so that's where the problem comes from.
For a Pycharm user the solution given by codeape works fine :
Snapshot
You can't use any IDE to run python files with the curses package. I used to run in pycharm and naturally couldn't run.
Change to the command line to run:
for testing follow my following steps
on desktop open notepad and copy paste the code and save it as filename.py
open command line change directory to desktop use below command cd Desktop and hit enter type python example.py and hit enter, your program will definitely run
My workaround is to create a Run Configuration that calls a curses script. The little overhead is worth not having to switch to the terminal and manually run the script hundreds of times a session. I use Intellij but I imagine the process should be similar in PyCharm.
The desired result is the convenience of a button to run the script:
First create a script that calls the entry script, for instance:
ptyhon name-of-script.py
Then, to create a configuration for each script:
Go to Edit configuration.
Click the plus button and add a Shell Script.
Enter the path to a shell script.
Here is a picture of a directory with a couple of sample scripts.
I use this process to view my progress. My curses scripts are very modest so fortunately I can live without a debugger.