Notepad++ Plugin To Run Python Scripts

I use Python everyday, it has become my first tool to use when I need to do anything. In Arabic (in Syrian Arabic specifically) I’d say that Python has become my hand and leg 😛

Yesterday I was writing a small Python script to read the YACC file and generate a list of all the specified rules inside it, so I don’t have to scroll through the long file to find out what rules are inside it 😉

I use Notepad++ as my default text editor on Windows, and I was writing the script using it – Notepad++. I wanted to test if the script is working, so I ran an instance of Command Line Prompt, and as I was going to change the directory to the directory of the script I thought; “Why doesn’t Notepad++ have a Run In Python command in it?”. So as usual I got pissed off and decided to create my own plugin to have that command in Notepad++ 8)

The Reference

I searched on the net, I found this Notepad++ Plugin Template, I edited it a little bit and I managed to do it :)

You can read below about the process and how it works, but if you just came here to download it click here.

The Process

To run a Python script; the plugin must do the following:

  • Get the path of the selected file in Notepad++.
  • Get the path of Python executable file, since not everyone has Python in the PATH environment variable.
  • Building the run command.
  • Execute the run command.

Get The Path of The Selected File In Notepad++

I also searched the net and found the following code:

The function sends a message to Notepad++ asking it to save the file before trying to run it, the result of the message will be either 1 which means that the file was saved, or 0 which means that the file wasn’t.
Then the function sends a message to Notepad++ asking it to put the full path of the currently selected file into a specific variable.
Now a little problem occurs when the file is unmodified, and the problem is that the first message will return 0 which means that the file wasn’t saved, while the second message will return a valid file path. So the function will search the path for a backslash which is the path separator in Windows, because a valid full path must contain at least one separator.
When the path is valid and the file is saved the function returns the path and sets the ok parameter to true, while in other cases it will return the path and set ok parameter to false.

Get The Path Of Python Executable File

The plugin will search for Python in its default path (“C:\Python[VER]”). If this method fails the plugin will search in registry for the key.

The Python installation path exists in the Windows Registry, so I wrote a small function to search the registry for the path and return it:

The code above accepts the root key as a parameter, and the code that calls it will call it twice, once with HKEY_CURRENT_USER and the other with HKEY_LOCAL_MACHINE, so it will try to find it in both locations HKEY_CURRENT_USER\Software\Python\PythonCore and HKEY_LOCAL_MACHINE\Software\Python\PythonCore.

Building The Run Command

The plugin allows the user to choose to run the file in interactive mode, so the window won’t disappear after the program is done. I’ve also added another thing, that is the ability to run the file in pythonw.exe instead of python.exe, and that’s for applications with GUI, so you don’t have to see a console window behind your application GUI 😉

This one would be very simple, just concatenate: Python installation path, “python.exe” and the full path of the current file.

Execute The Run Command

This function accepts a path parameter so it will run the process in the specified path (which is the path of the folder that includes the Python file to run) instead of the default path, this allows applications reading/writing files inside the same folder (or a relative path) of the application path to find those files.

This one is also simple, just create a new process with the run command.

Screenshot

PyNPP Notepad++ Plugin Screenshot

License

This work is licensed under GNU General Public License v3.

Download

PyNPP v1.2 on GitHub

GitHub

Plugin DLL:

Plugin DLL

Source Code

Source Code


Update History

  • 18, April 2010: PyNPP will search for Python in its default path C:\Python[VER]\.
  • 13, December 2010: PyNPP will allow the user to run the file in three modes: normal, interactive and GUI. As suggested by Andrew here.
  • 13, December 2010: PyNPP will run the file in its folder, so it can read/write files next to it. As suggested by Andrew here.
  • 03, January 2011: PyNPP will search for Python in both HKEY_CURRENT_USER\Software\Python\PythonCore and HKEY_LOCAL_MACHINE\Software\Python\PythonCore.
  • 05, January 2011: PyNPP will save the file before trying to run it.
    Fixed a bug in setting the current folder while running the process.
  • 12, August 2011: PyNPP allows you to select the Python folder using an options dialog. As suggested by Hönes here.
  • 21, December 2011: PyNPP moved to GitHub.
  • 27, April 2014: v1.1 released, PyNPP kills the Python instance it launches when the file is re-run. As suggested by Michał Kłopot.
  • 30, March 2015: v1.2 released, PyNPP supports debugging the file with PDB. As suggested by fdufnews.

101 thoughts on “Notepad++ Plugin To Run Python Scripts

  1. Hello,

    Interesting plugin. But unfortunately, I can’t install in the Notepad ++ v5.6.8.

    #Message#
    This Unicode plugin is not compatible with your ANSI mode Notepad++.

    This plugin is not compatible with current version of Notepad++.

    Do you have any idea?

    Thanks and Regards


  2. Razec:

    Hello,

    Interesting plugin. But unfortunately, I can’t install in the Notepad ++ v5.6.8.

    #Message#
    This Unicode plugin is not compatible with your ANSI mode Notepad++.

    This plugin is not compatible with current version of Notepad++.

    Do you have any idea?

    Thanks and Regards

    It seems that you have Notepad++ 5.6.8 (ANSI) installed.
    My plugin is a Unicode plugin, so you should install the Unicode version and the plugin will work :)

    But as I know Notepad++ are releasing only Unicode versions nowadays, I have the latest version and my plugin is working.

    Try installing the latest version instead of updating may be.

    Thanks.

  3. Hi Abd,

    You are right, I didn’t know there were two versions.

    Worked!! =)

    I now tested in other machine and show:
    “Could not locate Python”. But Python installed C:\Python25

    It happened because not found registry “HKEY_CURRENT_USER\Software\Python\PythonCore”
    Maybe future version, a user will configure the filename. =)

    Appreciate it, good job!!

    Thanks Very much

  4. Hi! I’m getting the same error as Razec. However i do have the registrykey and in the key PythonPath it says the right path.

    Couldn’t you just make a version that doesn’t check for the path and asumes you have the correct path? That would solve this for people like me and it would probably not be very hard for you to do. And the people who dont have the path set can just do so and solve it.

    Thank you!


  5. Alex:

    Hi! I’m getting the same error as Razec. However i do have the registrykey and in the key PythonPath it says the right path.

    Couldn’t you just make a version that doesn’t check for the path and asumes you have the correct path? That would solve this for people like me and it would probably not be very hard for you to do. And the people who dont have the path set can just do so and solve it.

    Thank you!

    I will do it very soon, I promise :)


  6. Dave Brotherstone:

    Just FYI, there’s now a full plugin for running Python scripts that integrates closely with Notepad++ – allowing you full access to modify the text and so on. http://npppythonscript.sourceforge.net/

    Thanks Dave, but are you sure it has the same functionality here? Because as far as I understood the plugin you’re maintaining is to manipulate Notepad++ from inside Python, while my plugin is too simple, it just executes the current file in an external Python shell.
    Anyway nice plugin 😉

  7. It can do that too – a script like

    reload(notepad.getCurrentFilename())

    will do it, won’t it?

    Anywho – as your plugin is not, as far as i know, on the list – I’ll add it to the plugin manager for you, and the wiki. You might want to post an announcement on the Plugin Development forum on the Notepad++ project page too… :)

    Cheers!

  8. I created myself HKEY_CURRENT_USER\Software\Python\PythonCore with proper path to Python, but Ur pligin still don’t work and I get “Could not locate Python”
    What it can be? :(

    1. Please make sure you downloaded the latest version of the plugin, and make sure that the path you added into the registry is a default key in: HKEY_CURRENT_USER\Software\Python\PythonCore\[VERSION]\InstallPath\. And that the path you added ends with a trailing backslash.
      Even if you don’t have the key in your registry the plugin will search for Python in its default path: C:\Python[VERSION]\, so you only have to do such thing when you don’t have Python installed in its default path.

      Hope this helps :)

      1. Hi Abd,

        I am having trouble running a python script using your plugin. When I try I get this error message:

        “Could not locate python”

        I have Notepad++ v5.8.6 (UNICODE) and installed your latest plugin as of 12/26/2010.

        I will appreciate any help.

        Thanks

        1. Please provide me with the full path of Python executable on your hard disk, and if you can show me the contents of this registry key: HKEY_CURRENT_USER\Software\Python\PythonCore\2.[VER]\InstallPath.

          1. Hi Abd Allah,

            My python is installed at C:\Program Files\Python27

            I could not find any Python under HKEY_CURRENT_USER\Software … Is this causing the problem? How can I ass Python here?

            Thanks a lot,
            KOP

            1. OK then, you don’t have Python installed in its default path – which should have been C:\Python27, and you don’t have it in your registry.
              You have two possible solutions here;
              you can either move your Python into the path it is supposed to be in ( C:\Python27), or you can set the keys in your registry manually.
              I’ve created a registry file for you, you can download it from here PyReg.reg and run it, it will create the necessary registry keys and values for you.

              Hope this helps.

  9. Great plugin! Though one little thing that bugged me was that when you run a python program that is reading/writing files in the same directory as the python source file (e.g. “./myfile.txt”), it would look for it under the directory containing the python.exe.

    So I modified your source a bit, to use the right path.

    in the PluginDefinition.cpp file, I modified:

    bool launchPython(std::wstring &command, std::wstring &path) //added the path param
    {
    STARTUPINFOW si;
    PROCESS_INFORMATION pi;
    memset(&si, 0, sizeof(si));
    memset(&pi, 0, sizeof(pi));
    si.cb = sizeof(si);

    return CreateProcess(
    NULL,
    const_cast(command.c_str()),
    NULL,
    NULL,
    FALSE,
    CREATE_DEFAULT_ERROR_MODE,
    NULL,
    const_cast(path.c_str()), //and put it in here
    &si,
    &pi) != 0;
    }

    //and under the void runFile() method I added:

    std::wstring path = L””;

    for(int i=file.length()-1;i>=0;i–) {
    if(file[i] == ‘\\’ || file[i] == ‘/’) {
    path = file.substr(0,i);
    break;
    }
    }

    //MessageBox(GetDesktopWindow(),path.c_str(),path.c_str(),0);

    if(!launchPython(command, path))

    Also this is optional, I modified this method to make the output window stay open after execution:

    std::wstring buildRunCommand(std::wstring &filePath, std::wstring &pypath)
    {
    std::wstring command = pypath;
    command += TEXT(“python.exe -i \””); //I just added -i here
    command += filePath;
    command += TEXT(“\””);
    return command;
    }

    I’d be very happy if you added these changes, thanks!

    1. Yeah that’s right Bernard :) But I like to do things the hard way 😉 And I think many people would rather having a plugin that doesn’t need configuration and easy to use, so they’re using this plugin instead.

    1. Then tell me please where you have Python installed and what values are in these registry keys: HKEY_CURRENT_USER\Software\Python\PythonCore and HKEY_LOCAL_MACHINE\Software\Python\PythonCore.

      P.S. Press the reply link on this comment so our conversation appears as a thread of nested comments 😉

      1. Yes, sorry I didn;t do that last time…
        I installed Python in D:\Programy\Python
        and in HKEY_CURRENT_USER\Software\Python\PythonCore i’ve got dir named 2.6, containing other dirs among which there is installpath dir with correct key value and pythonpath – also with valid values. In HKEY_LOCAL_MACHINE\Software there is no Python directory.
        Also: plugin doesn’t say he can’t LOCATE python. It’s say he can’t LAUNCH it. I saw that people above had problems with location, mine seems to be different (but you are the one who was writing error messages for that so you know best 😉 )
        Thanks for your time…

        1. OK then, you have another problem 😀
          Please download the DLL again and install it, I’ve added an error code to the message that says Couldn't launch Python..
          Try again and tell me what is the error code.
          Thanks for trying 😉

            1. Sorry for that 😳
              I’ve fixed that, but anyway the error code is 123 (0x7B). And it is ERROR_INVALID_NAME, which means that something is wrong with either the command the plugin is executing or the path of the folder it executes the command in, or maybe both.
              I’ve updated the plugin so that the message contains more info about those two parameters, please try again.

              And thanks really for trying and keeping with me 😀

                1. :(
                  It’s too bad that I can’t test it, and that you’ll have to test it every time :(
                  Can you please test it again? I know that you must have gotten bored by now, but please this way we’ll both make sure no one else gets this error again.

              1. Can’t press reply anymore, lol.
                And no worries, I’m stubborn and I want to have it working.
                The problem was… (you’re gonna get mad at me 😀 ) the file wasn’t saved! So i solved all my problems (for now), you’ll only have to add proper error message to remaind people like me to save the file first.
                Thanks a lot for or your hard work 😀 😀

  10. I’m just getting started with Python and found your plugin here for Npp — however it appears that it opens and runs the script in the windows command prompt. Is there any way to make this plugin run the scripts in the actual Python shell instead?

    Thanks for the awesome plugin BTW!

      1. He means like the excellent yet not completely polished SciTE does. NppExec shows it’s possible in NotePad++, but i couldn’t find a simple list of variables i could use in its rather confusing scripting interface.

  11. DOH! That’s embarrassing. Yeah IDLE is what I meant…but I guess that would defeat the purpose of this plugin to begin with so nevermind. I’m learning slowly here 😀 — thanks again!

  12. Actually, I’d like to thank you for this great plugin it saved my time.

    I’ve one problem that the python script runs only under the command window instead of running into the python shell.
    I tried to run it under python shell From Plug-ins > PyNPP > Run file in Pythonw and nothing happen.

    you’re help is highly appreciated.

    1. From what I know the Python shell is this one

      And when you use this plugin that’s what you’ll see (Plug-ins > PyNPP > Run file in Python).
      Running the file in PythonW is suitable for GUI applications, because it hides the Python shell.

      You might wanna run it in interactive mode (Plug-ins > PyNPP > Run file in Python Interactive) so that when the application ends you’ll still be able to see the shell.

  13. I wanted to keep the console open after running the script so I just added the “cmd /k ” command to the beginning of the buildRunCommand string variable.

    std::wstring buildRunCommand(std::wstring &filePath, std::wstring &pypath, bool isW = false, bool isI = false)
    {
    std::wstring command = TEXT(“cmd /k “) + pypath;
    command += TEXT(“python”);
    if (isW)
    command += TEXT(“w”);
    command += TEXT(“.exe “);
    if (isI)
    command += TEXT(“-i “);
    command += TEXT(“\””);
    command += filePath;
    command += TEXT(“\””);
    return command;
    }

  14. I have several Python version installed, cause of the different packages. But your plugin chooses automatically Python26.
    How can I change this. A feature, where I can change it by hand would be nice.

  15. I have found out, that your plugin chooses the first python in a row (I know you knew that already). As I renamed Python 32 in Python25, it choose the one I wanted. Of course that is no optionor solution. I think a lot of people would appreciate a simple version switch. Even in Ellipse it is a little bit clumsy. Just tell you that, because it is not just me, but you would advance your plugin over the average level. Only since your plugin I code Python in notepad++. Take your time, cause it could be a Killer feature for Notepad++, I am looking forward to it. Thanks a lot for your fast response.

  16. Thank you very much. Now I can switch between the different Python versions and play with it. Now notepad++ is the scripting editor of my choice. Grat work.

  17. Hey bud,

    I’m liking your plugin but unfortunately it’s not usable for the way I work with Python/Notepad++.

    The way I work now (and I believe many others work like this too) is that I have NPP open and a command line open, and use command history to repeat the last command to run my script after hitting Ctrl-S to save, sometimes editing the command line to include -i to troubleshoot.

    what would be ideal is if the plugin could be configured to reuse an already open command prompt to spawn the run command and leave the CMD open.

    When I run the script from NPP with your plugin, it flashes a window and closes it again. I’m not a fan of having to edit my code to force a window to remain open I believe this should be functionality of the plugin.

    Just my 2 cents bud,
    Thanks for sharing your work!

    1. I didn’t get you, why should it reuse an opened console to execute the script while it has an option of running the script in interactive mode? When you run it in interactive mode it won’t close after it finishes!

      Though it might be helpful if I edited the plugin to keep the console opened after running the script in normal mode.

      1. Command Prompt Python console. I know the console stays open with -i but that doesn’t help when you have to rerun your code after making a change.

        At this point I’d have to run it in interactive mode to see what my code did and exit it manually, change some code and run it again, close it, etc.

        What I meant with reusing an already open window I meant the Command Prompt that’s already open. Running a python script from the command line returns the command prompt when finished and leaves the output to be read. When, after changing some code it would be cool if the plugin would use the already open command prompt to rerun the script and simply return to the command prompt instead of closing the window.

        Hope I clarified it a bit, I don’t mean to put you up for any more work buddy, I just thought I’d share what I’d think would be handy that’s all :).

        1. Oke that’s weird, a few characters are removed from the post. I meant to say “Command prompt is not the same as python console”. I used greater than/less than signs but I guess those are not allowed.

  18. Hey,
    I am new to Python but have qute some knowledge in R.
    I really would like to use your script to execute and check my script (like NppToR). But unfortunately, when I start in interactive mode, python opens but my script is not running. What’s wrong?
    Cheers, UK

    1. What about starting the script in normal mode?
      Can you please try this for me?
      Open a command prompt in the folder that contains your script, then run the following command:

      python.exe -i YOUR_SCRIPT_NAME.py

      And tell me what happens then.

  19. Hey! Lovely little plugin you have here. Works fine for me but with one issue. Would it at all be possible for you to add the utf-8 (or similar) character encoding to it so that the prompt can print foreign letters such as European Å, Ä and Ö’s (etc). Would be great as this is currently keeping me from using this plugin as much as I would’ve liked to.

    Cheers

    1. I think this is a problem in windows console, if you open a console and try to print some Unicode characters in it, it’ll fail.
      To solve this you must execute the following command on your console:
      chcp 65001
      And change the console font to Lucida Console, and you’ll be able to print some Unicode characters in it.

  20. Simpler way:

    Go to Run -> “Run…”, then type in:

    C:\PythonXX\python.exe “$(FULL_CURRENT_PATH)”

    Save As – call it ‘Run file with Python’ and assign Ctrl+Alt+F5 shortcut….

    Add the -i switch and save as ‘Run with Python Interactive’ with Alt+Shift+F5 as shortcut

    Change exe to pythonw and save as …

    Well, you get the idea… 1 less level of Menu access to, if you don’t like shortcut key combos

    Also, just specify the Python exe in the ‘Run…’ dialolg, save it as ‘Run Python’ with a shortcut like Ctrl+Alt+P to get a bare interactive python shell…

    I suppose the plugin is easier if you need to reinstall…

  21. Hey, so I was using this plugin and, let me say, this plugin is AMAZING! I love using notepad ++

    But anyway, was using this plugin and couldn’t help but notice that it doesn’t seem to want to run pythonw!

    I’m using the latest python build and just got your plugin today so everything is current. This isn’t technically that big of a deal, unless I want to debug something, which means I’d have to open python up which SORT OF defeats the purpose of using notpad++.

    I’ll still use your plugin since… well it rocks but if you could look into this I would really appreciate it.

      1. Nothing happens. I click the option and that’s it. No window or anything :(
        Thanks for replying so fast by the way.

      2. Another thing, the program runs perfectly fine in pythonw, but I have to exit out and actually open pythonw manually. trying to get to it through notepad++ does nothing of course

      3. Hey Kalmaro,

        I tried it on Windows 7 x64 using the following code and it works:

        Can’t figure out what’s wrong with your program :S.
        Can you simplify your code as much as possible and try again? Just make it show a simple empty window.
        BTW, what GUI library are you using? I tried the plugin with a wxPython and PyQt4 and it works!

        See screenshots:

        1. Copy pasted your code, still no go. Not sure what python gui I’m using so going to download pyqt4 and try it out, will keep you posted

  22. I’ve always loved Notepad++, but never explored the depths of plug-ins. Shame on me, for all my time lost if I had only known about the Python linkages such as yours! This was so easy, that I suspect npp will now be my 100% editor for python programs. (I normally bounce between npp, spe, idle).. Between your plugin and the “Python Script” python console within npp, I’m a happy camper. I can’t wait to program exotic search-and-replace, or line extraction/bookmarking macros…

  23. I can’t run the option “Run file in PythonW”, that is there is not response. The previous two options (python interactive and python) are working without any problem. The python folder is the installation default that is C:\Python27 the python version is Python 2.7.6. I use Win 7 SP1 64 bit Pro edition and NPP++ 6.6.3 if that helps .

    1. Please note that PythonW means that your app will have to show its own GUI, no command line prompt will be shown, so the app should be a GUI app (wxPython, TkInter, PyQt, etc.) or you won’t see anything.

      1. Thank you about your quick response. Until now I was thinking that I could use the Python IDLE. Anyway thank you again, about your very useful plugin.

  24. Hi there!

    First of all, great job on the plugin, I love it!! I was trying out several Python IDEs and always thought the code editing capabilities were kind of lacking (e.g. no code snippets). But your plugin turns my favorite editor into all I need for comfortable scripting :-)

    I just have one question:
    I like to use Python mainly for data analysis, MATLAB-style. For this, it would be great for the “Run file in Python Interactive”-mode to use the last interactive console opened that way if there is already one. This way, you can play with variables using the console, run a script again to change them or add new ones, play with them again using the console ect. As I see it now, everytime you run the “Run file in Python Interactive”, the last console window closes and a new one is opened.
    Is there a way to implement this or do you know a quick workaround to do it?

    Also, if you want to add even more features to your already awesome plugin, a feature to run only a selection of the code would sometimes be helpful 😉

    Best regards,
    Sebastian

    1. Thanks :)

      When running in Python interactive, every time the plugin will run a new Python instance, it can’t communicate with the instance afterwards, that’s why it will need to run different instance each time, but if you run your code in interactive mode the window will stay open after the code finishes so that you can interact with it.

      About running only a part of the code I’m not sure if it’s possible, but will look into it when I have the chance.

  25. Thanks a lot for this plugin, could you consider adding an new item in the list to launch a script with pdb library to help debug, like:
    python -m pdb scriptname.py

  26. Thanks a lot for this plugin.
    Tip for people who do not know :
    Changing the shortcuts:
    Notepad++ toolbar–> macro–> Modify Shortcut/Delete Macro..–>Plugin commands

  27. Seems not compatible with Portable Python 2.7.6.1. However, I installed regular Python 2.7, then copied the entire directory where it was installed into a flash drive and the plugin worked with it. Although, that is all i need, perhaps you may want to look at why not with Portable Python

Leave a Reply