how to configure the hotkey of notepad++ for python? - python

hi I am using notepad++ for python.
I want a hotkey that will run my python script at the path of the script instead of the path of notepad++.
Besides, at the end of process, i want it to show "press any key to continue".
I've tried:
cmd /k "$(FULL_CURRENT_PATH)"
python "$(FULL_CURRENT_PATH)"
But none of them meets my expectations.
For example:
f = open('hello.txt', 'w')
f.close()
This will create 'hello.txt' in the directory of notepad++, but I want to create it at the same path of this script.

That's a good find - Notepad++ seems to always set the current working directory to it's own executable directory when scripts are run.
One workaround is to use this: Notepad++ Python Plug-in. This is a plug-in for Notepad++ and adds options to run your scripts in Python from the Plugins menu in Notepad++ (instead of using the Run menu). This should fix your current working directory problem.

Related

How to run python script without writing command on cmd again and again

I am practicing python code and executing it through command line. each time i have to execute my python file i go to cmd and write
D:\PythonPractice>python myClass.py
Is there any standard and comfortable way available to execute python code quickly?
If you are executing the same command, with no changes to arguments or anything, you can pack it in a .bat file (windows executable)
Name it something like myscript.bat
D:\PythonPractice>python C:\path\to\myClass.py
Put full path inside it. Now double click will do.
Use PyCharm Software by JetBrains (same company who developed Android studio and Kotlin language), it will help you in many ways .
Run Python with single press of a button.
Add modules easily just with some clicks.
Debugging the code as smooth as possible.
It is Awesome, I am using it for past couple of months.
you can change file association which controls what to do when invoking filename in command line. For instance, when you just type text filename in cmd, notepadd will be opened, for word docs Word or other document editor.
Have a look into following link from google or you can fiddle by yourself starting from Control Panel > Control Panel Home > Default Programs > Set Associations. Select a file type in the list and click Change Program.
Alternatively,you can use any of Python IDE (PyCharm,PyDev etc.) so you will be able to run directly scripts from editor.
With Notepad++, you can also create a shortcut to be able to launch your python script :
Menu Run > Run (or press F5)
Choose the python .exe (default in C:\Program Files (x86)\Python36-32\python.exe
Then add this code next to the path : "$(FULL_CURRENT_PATH)"
This will allow to execute the current file
example of command with Python 3.6 :
"C:\Program Files (x86)\Python36-32\python.exe" "$(FULL_CURRENT_PATH)"
Then save the command, by assigning a shorcut key, it's better with a modifier like SHIFT (SHIFT + F10)
Now you can launch any script with this shortcut.

Running Python file by double-click

I have really annoying problem, I cannot run a Python file just by double-clicking.
I have tried to set it to open the file with idle.bat but that only starts IDLE editor on double-click, it does not run the Python file.
What version of Python do you have installed?
You should write your own batch file to execute your python binary and your script.
For example, with a default Python 2.7 installation on Windows, this could be the entire contents of your script.
myscript.bat:
ECHO ON
REM A batch script to execute a Python script
SET PATH=%PATH%;C:\Python27
python yourscript.py
PAUSE
Save this file as "myscript.bat" (make sure it's not "myscript.bat.txt"), then double click it.
right click on the file->open with->choose default program->more options->select python.exe file and click on.
Right click the file, select open with. If you want to simply run the script, find python.exe and select it. If you want to debug with IDLE, find that executable and select it.
When I had both Py2 and Py3, and then removed the former, my script wouldn't run by double-clicking it either (but fine from console.) I realized my __pycache__ folder (same directory as the script) was the issue. Problem solved when deleted.
You can also start a Django app this way. Once the Django server starts it enters a "wait" kind of mode so a batch file only requires two lines:
ECHO ON
python manage.py runserver
Manage.py can be in any directory, just keep the full folder path in the command within the batch file:
ECHO ON
python C:\temp\manage.py runserver
Solution for Ubuntu users.
Right-click on the file, then select open with, then choose your python version, it shode be in
/bin folder, usually it's /bin/python3.exe
In Windows 10, using regedit:
Under HKEY_CLASSES_ROOT, create key: .py
Edit Default string value to be py_auto_file (or any other name you want to call it)
Under HKCR, create another key: py_auto_file (or any matching name that you have just picked)
Under this key, create nested sub-keys: shell --> open --> command.
Edit Default string value to "C:\path\to\your\python.exe" "%1"

Keep Windows Console open after a Python Error

File associations on my machine (winxp home) are such that a python script is directly opened with the python interpreter. If I double click on a python script a console window runs and every thing is fine - as long as there is no syntax error in the script.
In that case the console window opens up for a moment but it is closed immediately. Too fast to read the error message.
Of course their would be the possibility to manually open a console window and to execute the script by typing python myscript.py but I am sure that there is a more convenient (i.e. "double click based") solution.
Make a batch file:
C:\Python26\python.exe %1
IF %ERRORLEVEL% NEQ 0 PAUSE
Use that as your file association instead of python.exe directly. This will only cause the PAUSE statement to execute if python.exe returns an error
The canonical way to run a command in a command prompt window that doesn't close is
cmd /k "your command"
The way that I do it is i right click the script that I saved from notepad to a .py file, then i click edit with IDLE, This is an editing thingy, but you can also run modules from it
I've left a comment at rossipedia's answer about a similar situation, but I doubt it's gonna get noticed in a 8 year old post. So, I've experimented myself.
I have a python script that processes a folder that's dropped on it. As I add new lines, sometimes I get syntax errors, and I can't view them because the command prompt window closes too quickly. In order to keep the window open after an error, I had to modify rossipedia's code. I needed a way to pass a path to the bat file (drop a folder on it) and make the bat pass that path to the python script. The following does that:
debug.bat:
#echo off
REM debug.bat and myscript.py should be in the same dir, otherwise use absolute path for the python script
C:\Users\%username%\AppData\Local\Programs\Python\Python36-32\python.exe "%~dp0\myscript.py" %1
IF %ERRORLEVEL% NEQ 0 PAUSE
myscript.py:
import sys
print("printing dropped file path:")
print(sys.argv[1])
input()
If I get an error, I just use the debug.bat to view the error, and it works the same (drop a folder on it).
Update:
In my actual python script, I have this line:
sys.path.append("modules")
This doesn't work when I use debug.bat. "modules" is a folder that's in the same folder with the python script. When the script is called with debug.bat, the current working directory changes to the dropped file's directory. So, to get the path to "modules", I had to use absolute path:
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "\\modules")

How to Execute a Python Script in Notepad++?

I prefer using Notepad++ for developing,
How do I execute the files in Python through Notepad++?
First option: (Easiest, recommended)
Open Notepad++. On the menu go to: Run -> Run.. (F5). Type in:
C:\Python26\python.exe "$(FULL_CURRENT_PATH)"
Now, instead of pressing run, press save to create a shortcut for it.
Notes
If you have Python 3.1: type in Python31 instead of Python26
Add -i if you want the command line window to stay open after the script has finished
Second option
Use a batch script that runs the Python script and then create a shortcut to that from Notepad++.
As explained here: http://it-ride.blogspot.com/2009/08/notepad-and-python.html
Third option: (Not safe)
The code opens “HKEY_CURRENT_USER\Software\Python\PythonCore”, if the key exists it will get the path from the first child key of this key.
Check if this key exists, and if does not, you could try creating it.
#Ramiz Uddin's answer definitely deserves more visibility :
Open Notepad++
On the menu go to: Run → Run.. (F5)
Type in: cmd /K python "$(FULL_CURRENT_PATH)"
Here is what's worked for me:
Open notepad++ and press F5. You'll get a little popup box:
Type: C:\Python27\python.exe -i "$(FULL_CURRENT_PATH)" for Python 2.7.
and then Save As..., and pick your own key combo to start it each time you want to run something
I also wanted to run python files directly from Notepad++.
Most common option found online is using builtin option Run. Then you have two options:
Run python file in console (in Windows it is Command Prompt) with code something like this (links: ):
C:\Path\to\Python\python.exe "$(FULL_CURRENT_PATH)"
(If your console window immediately closes after running then you can add cmd /k to your code. Links: ) This works fine, and you can even run files in interactive mode by adding -i to your code (links: ).
Run python program in IDLE with code something like this (links: , in these links C:\Path\to\Python\Lib\idlelib\idle.py is used, but I am using C:\Path\to\Python\Lib\idlelib\idle.bat instead, because idle.bat sets the right current working directory automatically):
C:\Path\to\Python\Lib\idlelib\idle.bat "$(FULL_CURRENT_PATH)"
Actually, this doesn't run your program in IDLE Shell, but instead it opens your python file in IDLE Editor and then you need to click Run Module (or click F5) to run the program. So it opens your file in IDLE Editor and then you need run it from there, which defeats the purpose of running python files from Notepad++.
But, searching online, I found option which adds '-r' to your code (links: ):
C:\Path\to\Python\Lib\idlelib\idle.bat -r "$(FULL_CURRENT_PATH)"
This will run your python program in IDLE Shell and because it is in IDLE it is by default in interactive mode.
Problem with running your python files via builtin Run option is that
each time you run your python file, you open new console or IDLE window and lose all output from previous executions. This might not be important to some, but when I started to program in python, I used Python IDLE, so I got used to running python file multiple times in same IDLE Shell window. Also problem with running python programs from Notepad++ is that you need to manually save your file and then click Run (or press F5). To solve these problems (AFAIK*) you need to use Notepad++ Plugins. The best plugin for running python files from Notepad++ is
NppExec. (I also tried PyNPP and Python Script. PyNPP runs python files in console, it works, but you can do that without plugin via builtin Run option and Python Script is used for running scripts that interact with Notepad++ so you can't run your python files.) To run your python file with NppExec plugin you need to go to Plugins -> NppExec -> Execute and then type in something like this (links: ):
C:\Path\to\Python\python.exe "$(FULL_CURRENT_PATH)"
With NppExec you can also save your python file before run with npp_save command, set working directory with cd "$(CURRENT_DIRECTORY)" command or run python program in interactive mode with -i command. I found many links ( ) online that mention these options, but best use of NppExec to run python programs I found at NppExec's Manual which has chapter 4.6.4. Running Python & wxPython with this code:
npp_console - // disable any output to the Console
npp_save // save current file (a .py file is expected)
cd "$(CURRENT_DIRECTORY)" // use the current file's dir
set local #exit_cmd_silent = exit() // allows to exit Python automatically
set local PATH_0 = $(SYS.PATH) // current value of %PATH%
env_set PATH = $(SYS.PATH);C:\Python27 // use Python 2.7
npp_setfocus con // set the focus to the Console
npp_console + // enable output to the Console
python -i -u "$(FILE_NAME)" // run Python's program interactively
npp_console - // disable any output to the Console
env_set PATH = $(PATH_0) // restore the value of %PATH%
npp_console + // enable output to the Console
All you need to do is copy this code and change your python directory if you use some other python version (e.g.* I am using python 3.4 so my directory is C:\Python34). This code works perfectly, but there is one line I added to this code so I can run python program multiple times without loosing previous output:
npe_console m- a+
a+ is to enable the "append" mode which keeps the previous Console's text and does not clear it.
m- turns off console's internal messages (those are in green color)
The final code that I use in NppExec's Execute window is:
npp_console - // disable any output to the Console
npp_save // save current file (a .py file is expected)
cd "$(CURRENT_DIRECTORY)" // use the current file's dir
set local #exit_cmd_silent = exit() // allows to exit Python automatically
set local PATH_0 = $(SYS.PATH) // current value of %PATH%
env_set PATH = $(SYS.PATH);C:\Python34 // use Python 3.4
npp_setfocus con // set the focus to the Console
npe_console m- a+
npp_console + // enable output to the Console
python -i -u "$(FILE_NAME)" // run Python's program interactively
npp_console - // disable any output to the Console
env_set PATH = $(PATH_0) // restore the value of %PATH%
npp_console + // enable output to the Console
You can save your NppExec's code, and assign a shortcut key to this NppExec's script. (You need to open Advanced options of NppExec's plugin, select your script in the Associated script drop-down list, press the Add/Modify, restart Notepad++ , go to Notepad++'es Settings -> Shortcut Mapper -> Plugin commands, select your script, click Modify and assign a shortcut key. I wanted to put F5 as my shortcut key, to do that you need to change shortcut key for builtin option Run to something else first.) Links to chapters from NppExec's Manual that explain how to save you NppExec's code and assign a shortcut key: NppExec's "Execute...", NppExec's script.
P.S.*: With NppExec plugin you can add Highlight Filters (found in Console Output Filters...) that highlight certain lines. I use it to highlight error lines in red, to do that you need to add Highlight masks: *File "%FILE%", line %LINE%, in <*> and Traceback (most recent call last): like this.
First install Python from https://www.python.org/downloads/
Run the installer
** IMPORTANT **
Be sure you check both :
Install launcher for all users
Add Python 3.6 to path
Click install now and finish the installation.
Open notepad++ and install plugin PyNPP from Plugin Manager. I'm using N++ 6.9.2
Save a new file as new.py
Type in N++
import sys
print("Hello from Python!")
print("Your Python version is: " + sys.version)
Press Alt+Shift+F5
Simple as that.
On the menu go to: "Run" --> "Run..." (or just press F5).
For Python 2 type in:
py -2 -i "$(FULL_CURRENT_PATH)"
For Python 3 type in:
py -3 -i "$(FULL_CURRENT_PATH)"
References:
To understand the py command better:
py -h
Another helpful link to understand the py command: How do I run python 2 and 3 in windows 7?
Thanks to Reshure for his answer that got me on the right track to figure this out.
All the answers for the Run->Run menu option go with the "/K" switch of cmd, so the terminal stays open, or "-i" for python.exe so python forces interactive mode - both to preserve the output for you to observe.
Yet in cmd /k you have to type exit to close it, in the python -i - quit(). If that is too much typing for your liking (for me it sure is :), the Run command to use is
cmd /k C:\Python27\python.exe "$(FULL_CURRENT_PATH)" & pause & exit
C:\Python27\python.exe - obviously the full path to your python install (or just python if you want to go with the first executable in your user's path).
& is unconditional execution of the next command in Windows - unconditional as it runs regardless of the RC of the previous command (&& is "and" - run only if the previous completed successfully, || - is "or").
pause - prints "Press any key to continue . . ." and waits for any key (that output can be suppressed if need).
exit - well, types the exit for you :)
So at the end, cmd runs python.exe which executes the current file and keeps the window opened, pause waits for you to press any key, and exit finally close the window once you press that any key.
None of the previously proposed solutions worked for me. Slight modification needed.
After hitting F5 in Notepad++, type:
cmd /k "C:\Python27\python.exe $(FULL_CURRENT_PATH)"
The command prompt stays open so you can see the output of your script.
I use the NPP_Exec plugin (Found in the plugins manager). Once that is installed, open the console window (ctrl+~) and type:
cmd
This will launch command prompt. Then type:
C:\Program Files\Notepad++> **python "$(FULL_CURRENT_PATH)"**
to execute the current file you are working with.
I wish people here would post steps instead of just overall concepts. I eventually got the cmd /k version to work.
The step-by-step instructions are:
In NPP, click on the menu item: Run
In the submenu, click on: Run
In the Run... dialog box, in the field The Program to Run, delete any existing text and type in: cmd /K "$(FULL_CURRENT_PATH)"
The /K is optional, it keeps open the window created when the script runs, if you want that.
Hit the Save... button.
The Shortcut dialogue box opens; fill it out if you want a keyboard shortcut (there's a note saying "This will disable the accelerator" whatever that is, so maybe you don't want to use the keyboard shortcut, though it probably doesn't hurt to assign one when you don't need an accelerator).
Somewhere I think you have to tell NPP where the Python.exe file is (e.g., for me: C:\Python33\python.exe). I don't know where or how you do this, but in trying various things here, I was able to do that--I don't recall which attempt did the trick.
My problem was, as it was mentioned by copeland3300, that my script is running from notepad++ folder, so it was impossible to locate other project files, such as database file, modules etc. I solved the problem using standard notepad++ "Run" command (F5) and typing in:
cmd /k "cd /d "$(CURRENT_DIRECTORY)" & python "$(FULL_CURRENT_PATH)""
Python WAS in my PATH. Cmd window stayed open after script finished.
No answer here, or plugin i found provided what i wanted. A minimalist method to launch my python code i wrote on Notepad++ with the press of a shortcut, with preferably no plugins.
I have Python 3.6 (64-bit), for Windows 8.1 x86_64 and Notepad++ 32bit. After you write your Python script in Notepad++ and save it, Hit F5 for Run. Then write:
"C:\Path\to\Python\python.exe" -i "$(FULL_CURRENT_PATH)"
and hit the Run button. The i flag forces the terminal to stay still after code execution has terminated, for you to inspect it. This command will launch the script in a cmd terminal and the terminal will still lie there, until you close it by typing exit().
You can save this to a shortcut for convenience (mine is CTRL + SHIFT + P).
I would like to avoid using full python directory path in the Notepad++ macro. I tried other solutions given in this page, they failed.
The one working on my PC is:
In Notepad++, press F5.
Copy/paste this:
cmd /k cd /d "$(CURRENT_DIRECTORY)" && py -3 -i "$(FULL_CURRENT_PATH)"
Enter.
There is one issue that I didn't see resolved in the above solutions. Python sets the current working directory to wherever you start the interpreter from. If you need the current working directory to be the same directory as where you saved the file on, then you could hit F5 and type this:
cmd /K cd "$(CURRENT_DIRECTORY)"&C:\Users\username\Python36-32\python.exe -i "$(FULL_CURRENT_PATH)"
Except you would replace C:\Users\username\Python36-32\python.exe with whatever the path to the python interpreter is on your machine.
Basically you're starting up command line, changing the directory to the directory containing the .py file you're trying to run, and then running it. You can string together as many command line commands as you like with the '&' symbol.
Extending Reshure's answer
Open Run → Run... from the menubar in Notepad++ (shortcut: F5)
In the given space, enter:
"$(FULL_CURRENT_PATH)" -1
Click Run
ta da!
I started using Notepad++ for Python very recently and I found this method very easy. Once you are ready to run the code,right-click on the tab of your code in Notepad++ window and select "Open Containing Folder in cmd". This will open the Command Prompt into the folder where the current program is stored. All you need to do now is to execute:
python
This was done on Notepad++ (Build 10 Jan 2015).
I can't add the screenshots, so here's a blog post with the screenshots - http://coder-decoder.blogspot.in/2015/03/using-notepad-in-windows-to-edit-and.html
In Notepad++, go to Run → Run..., select the path and idle.py file of your Python installation:
C:\Python27\Lib\idlelib\idle.py
add a space and this:
"$(FULL_CURRENT_PATH)"
and here you are!
Video demostration:
https://www.youtube.com/watch?v=sJipYE1JT38
In case someone is interested in passing arguments to cmd.exe and running the python script in a Virtual Environment, these are the steps I used:
On the Notepad++ -> Run -> Run , I enter the following:
cmd /C cd $(CURRENT_DIRECTORY) && "PATH_to_.bat_file" $(FULL_CURRENT_PATH)
Here I cd into the directory in which the .py file exists, so that it enables accessing any other relevant files which are in the directory of the .py code.
And on the .bat file I have:
#ECHO off
set File_Path=%1
call activate Venv
python %File_Path%
pause
You can run your script via cmd and be in script-directory:
cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)
I usually prefer running my python scripts on python native IDLE interactive shell rather than from command prompt or something like that. I've tried it, and it works for me. Just open "Run > Run...", then paste the code below
python -m idlelib.idle -r "$(FULL_CURRENT_PATH)"
After that, you can save it with your hotkey.
You must ensure your desired python is added and registered in your environment variables.
In addition to the many other answers about using a system-wide installation of a Python interpreter, there is also a Python plugin for Notepad++. I've used it many times, and it works quite well. You can even assign shortcut keys to run specific Python scripts.
It is open-source and gratis (free of charge).
The source code and plugin are located here:
https://github.com/bruderstein/PythonScript/

Drag and drop onto Python script in Windows Explorer

I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.
Is there some kind of configuration that needs to be done somewhere for this work?
Sure. From a mindless technology article called "Make Python Scripts Droppable in Windows", you can add a drop handler by adding a registry key:
Here’s a registry import file that you can use to do this. Copy the
following into a .reg file and run it
(Make sure that your .py extensions
are mapped to Python.File).
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler]
#="{60254CA5-953B-11CF-8C96-00AA00B8708C}"
This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with 86C86720-42A0-1069-A2E8-08002B30309D.
A comment in that post indicates that one can enable dropping on "no console Python files (.pyw)" or "compiled Python files (.pyc)" by using the Python.NoConFile and Python.CompiledFile classes.
write a simple shell script (file.bat)
"C:\python27\python.exe" yourprogram.py %*
where %* stands for the all arguments you pass to the script.
Now drag & drop your target files on the file.bat icon.
With an installed python - at least 2.6.1 - you can just drag and drop any file on a python script.
import sys
droppedFile = sys.argv[1]
print droppedFile
sys.argv[0] is the script itself. sys.argv[n+1] are the files you have dropped.
Try using py2exe. Use py2exe to convert your python script into a windows executable. You should then be able to drag and drop input files to your script in Windows Explorer. You should also be able to create a shortcut on your desktop and drop input files onto it. And if your python script can take a file list you should be able to drag and drop multiple files on your script (or shortcut).
Create a shortcut of the file. In case you don't have python open .py files by default, go into the properties of the shortcut and edit the target of the shortcut to include the python version you're using. For example:
Target: C:\Python26\python.exe < shortcut target path>
I'm posting this because I didn't want to edit the Registry and the .bat workaround didn't work for me.
1). create shortcut of .py
2). right click -> properties
3). prefix "Target:" with "python" so it runs the .py as an argument into the python command
or
1). create a .bat
2). python some.py %*
these shortcut versions are simplest for me to do what i'm doing
otherwise i'd convert it to a .exe, but would rather just use java or c/c++
Late answer but none of the answers on this page worked for me.
I managed to enable/fix the drag and drop onto .py scripts using:
HKEY_CLASSES_ROOT\.py -> Set default value to Python.File
HKEY_CLASSES_ROOT\Python.File\Shell\Open -> Create a key called Command with default value "C:\Windows\py.exe" "%1" %*
CLASSES_ROOT\Applications\py.exe\open\command -> Create keys if the don't exist and set the default value to "C:\Windows\py.exe" "%1" %*
CLASSES_ROOT\Python.File\ShellEx -> create key DropHandler with default value {86C86720-42A0-1069-A2E8-08002B30309D}
That's it. Test it by dragging a file onto the python script:
import sys
args = sys.argv
print(args)
For those who use argv in .py script but still can't drag files to execute,
this could be solved by simply using Python Launcher (with rocket icon)
the script property "Open File" was set as python.exe,
which has no knowledge that the script needs command-line arguments "%*"
Refer to: https://bugs.python.org/issue40253

Categories

Resources