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.
Related
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.
I am using Python 3.3 (2.7 is also installed) and a compatible version of pygame. Recently I have been trying to switch from IDLE to Notepad++
I am using a saved shortcut in Notepad++
C:\Python33\python.bat "$(CURRENT_DIRECTORY)" "$(FILE_NAME)"
which runs the batch file:
#echo off
cd %1
%2
if not errorlevel 1 goto quit
echo.
echo.
pause
:quit
When I run C:\Python33\Foldername\imp_prob.py
import pygame
in IDLE it works fine, in Notepad++ using that shortcut it gives an ImportError: No module named pygame
My questions are:
Why is the NP++ method not producing the same result?
How can I change the shortcut or batch file to make it run stuff that IDLE can run?
What method can I use to ensure that I can import a module regardless of which directory I am running the program from?
edit: a working alternative was in the answers to How do you run a python script from within notepad++?
I had some issues with the code they provided, but replacing "python" with the full path to my python33 install solved that.
I still don't understand why pygame wouldn't import when using my run shortcut. I also don't understand why NppExec works when Run doesn't.
It sounds like you would need to set your systemvariables. Idle does not require these steps. You entered the full path to the python.exe in np++ to execute the python program, but the path to the modules etc. is still unknown.
Add the paths, and try again.
System Properties -> Advanced -> Environment Variables, in the bottom window look for a "Path" variable, Edit and append the following the existing entries (do not delete anything in there!)
;C:\Python33;C:\Python33\DLLs;C:\Python33\Lib
for Python 3.3, if you have installed it into its default directory.
To see if everything worked, open the console anywhere (shift+rightclick -> Open Command Window Here) and just type "python". The python console should open, telling you that you use python 3.3. You then also do not need to tell np++ the full python path, but instead can just use "python" again.
This is a weird bug. I know it's something funky going on with my PATH variable, but no idea how to fix it.
If I have a script C:\Test\test.py and I execute it from within IDLE, it works fine. If I open up Command Prompt using Run>>cmd.exe and navigate manually it works fine. But if I use Windows 7's convenient Right Click on folder >> Command Prompt Here then type test.py it fails with import errors.
I also cannot just type "python" to reach a python shell session if I use the latter method above.
Any ideas?
Edit: printing the python path for the command prompt that works yields the correct paths. Printing it on the non-working "Command prompt here" yields: Environment variable python not defined".
First of all, I work on Windows7 (among others) and running python from the command line works for me using "Command Prompt Here". Make sure you have the directory containing python.exe in your PATH environment variable, by running "Command Prompt Here" and running set.
Now for import errors. When importing, Python looks for modules in directories specified in the sys.path list. The PYTHONPATH environment variable is added to this list, along with some default directories, and the directory of the given Python script. However, in IDLE this directory is the directory of IDLE, so this could be causing the difference you are seeing when running things from IDLE compared to running them from the command line.
See http://docs.python.org/tutorial/modules.html#the-module-search-path for details.
Here is my advice on how to resolve this issue. You didn't mention what import errors you are recieving, but try running the script inside IDLE and checking the problematic modules' .__file__ attribute to see where they are. Then compare the sys.path from inside IDLE to sys.path you get when running Python from the command line. This should give you the information required to resolve your import errors.
I don't use Windows much, but maybe when you open Right Click -> Command Prompt, the PATH is different from navigate manually. First try to print your PATH (oh I have no ideal how to do this) and see if it different in 2 situation.
You can check the currently present enviroment variables with the "set" command on the command line. For python to work you need at least PYTHONPATH pointing to your python libs and the path to python.exe should be included in your PATH variable.
How do I run a Python file from the Windows Command Line (cmd.exe) so that I won't have to re-enter the code each time?
Wouldn't you simply save your Python code into a file, and then execute that file using Python?
Save your code into a file called Test.py.
And then run it?
$ C:\Python24\Python.exe C:\Temp\Test.py
If you don't want to install an IDE, you can also use IDLE which includes a Python editor and a console to test things out, this is part of the standard installation.
If you installed the python.org version, you will see an IDLE (Python GUI) in your start menu. I would recommend adding it to your Quick Launch or your desktop - whatever you are most familiar with. Then right-click on the shortcut you have created and change the "Start in" directory to your project directory or a place you can mess with, not the installation directory which is the default place and probably a bad idea.
When you double-click the shortcut it will launch IDLE, a console in which you can type in Python command and have history, completion, colours and so on. You can also start an editor to create a program file (like mentioned in the other posts). There is even a debugger.
If you saved your application in "test.py", you can start it from the editor itself. Or from the console with execfile("test.py"), import test (if that is a module), or finally from the debugger.
If you put the Python executable (python.exe) on your path, you can invoke your script using python script.py where script.py is the Python file that you want to execute.
Open a command prompt, by pressing Win+R and writing cmd in that , navigate to the script directory , and write : python script.py
A good tool to have is the IPython shell. Not only can it run your program (%run command), but it offers also many tools for using Python interactively in an efficient manner (automatic completion, syntax coloring, quick access to the documentation, good interaction with Matplotlib,…). After you install it, you'll have access to its shell in the Start menu.
You need to create environment variables. Follow the instructions here: http://www.voidspace.org.uk/python/articles/command_line.shtml#environment-variables
In DOS you can use edit to create/modify text files, then execute them by typing python [yourfile]