- Скрипт для Notepad++ на Python
- Постановка задачи
- Решение
- How To Use Notepad++ To Run Python – A Complete Guide
- Method 1: Utilizing Option Run In Notepad++ To Run Python
- Method 2: Utilizing PyNPP Plugin In Notepad++ To Run Python
- The Bottom Line
- Run Python in Notepad++
- Run Python File Using Run Option in Notepad++
- Run Python File Using PyNPP Plugin in Notepad++
- Related Article — Python Run
- Notepad++ Run Python Script: A Completed Guide – Python Tutorial
- Preliminary
- Create a python file
- Press Run or F5 on the notepad++
- Set the path of python script
- Save command
Скрипт для Notepad++ на Python
Думаю, многим известен — удобная бесплатная утилита, выступающая в качестве «продвинутой» замены стандартному Блокноту Windows. Как и при работе в любом текстовом редакторе, в Notepad++ время от времени возникает необходимость автоматизировать какие-либо повторяющиеся действия, которые в силу сложности логики невозможно записать как макрос. К счастью, для решения этой задачи нет необходимости переключаться из в, например, Word, дабы воспользоваться встроенным в него VB.
Среди плагинов для существуют расширения, реализующие возможность написания скриптов для на разных языках, таких как JavaScript, Lua, PHP или Python. Именно на последнем я и решил остановиться для решения своей задачи.
Постановка задачи
Предположим, перед нами стоит следующая задача (взята из жизни).
- пронумеровать символы ‘@’, находящиеся в начале строки, заменив ‘@’ на ‘@1’, ‘@2’ и т.д.;
- удалить пустые (включая пробелы и табуляцию) строки, идущие подряд по две и более.
3. Если в выделенном фрагменте текста (или во всём документе — в случае если нет выделения) отсутствует символ ‘@’, должно выводиться соответствующее сообщение об ошибке.
- по нажатию соответствующей кнопки на панели инструментов;
- с помощью клавиатурного сочетания;
- через контекстное меню правой кнопки мыши.
Решение
Для начала нам потребуется установить плагин для под названием Python Script. С его помощью можно производить любые операции с редактируемым текстом, открывать/закрывать файлы, переключать вкладки, выполнять команды меню и т.д. — одним словом, практически всё, что вообще можно сделать в .
Далее, выбрав в меню Plugins->Python Script->New Script, создаём скрипт:
# -*- coding: utf-8 -*- #Скрипт для Notepad++, удаляющий пустые строки и нумерующий символы "@", находящиеся в начале строки # Получаем выделенный текст text = editor.getSelText() isSelection = True # Если текст не выделен, то работаем со всем документом if not text: isSelection = False text = editor.getText() #Находим количество вхождений символа "@", находящегося в начале строки import re occurrencesCount = len(re.findall('^@', text, flags=re.MULTILINE)) # Если в тексте нет ни одного символа "@" в начале строки, выводим сообщение об ошибке if occurrencesCount == 0: notepad.messageBox('В тексте должен присутствовать как минимум 1 символ "@" в начале строки', 'Неверный формат входных данных', MESSAGEBOXFLAGS.ICONEXCLAMATION) # Если символ "@" присутствует, то else: countStartFrom = '' # Выдаём запрос до тех пор, пока не будет введено число while not countStartFrom.isdigit(): countStartFrom = notepad.prompt('Введите число, с которого должна начинаться нумерация вхождений в тексте символа "@":', 'Нумерация вхождений символа "@"', '1') if countStartFrom == None: break if countStartFrom != None: # Удаление пустых строк text = re.sub('\r\n\\s*\r\n', '\r\n', text) # Удаление пустой строки в конце и в начале файла/выделения text = re.sub('\r\n\s*$|^\s*\r\n', '', text, flags=re.MULTILINE) # Переводим countStartFrom из строки в целочисленный тип countStartFrom = int(countStartFrom) # Функция, возвращающая символ "@" с добавленным к нему и увеличенным номером def addNumber(matchobj): global countStartFrom countStartFrom += 1 return '@'+str(countStartFrom-1) #Добавляем нумерацию ко всем символам "@", находящимся в начале строки text = re.sub('^@', addNumber, text, flags=re.MULTILINE) #Заменяем обработанной строкой выделение или весь документ if isSelection: editor.replaceSel(text) else: editor.setText(text)
Если мы назвали скрипт «Empty Lines And Count», то запустить его можно из меню Plugins->Python Script->Scripts->Empty Lines And Count. Чтобы добавить его кнопку на панель инструментов и сделать возможным запуск по клавиатурному сочетанию, в настройках плагина (Plugins->Python Script->Configuration) выбираем созданный нами скрипт и добавляем его в меню и на панель инструментов. Теперь после перезапуска соответствующая кнопка появится на панели инструментов.
Назначить скрипту сочетание клавиш можно в меню Settings->Shortcut mapper в разделе Plugin commands.
Чтобы добавить скрипт в контекстное меню , нужно в xml-файл настроек (Settings->Edit Popup ContextMenu) добавить в нужном вам месте (например, перед первым элементом) следующие строчки:
Вот и всё. Теперь даже рутинные действия со сложной логикой можно выполнять одним кликом.
How To Use Notepad++ To Run Python – A Complete Guide
Many have struggled with utilizing Notepad++ to run Python. Are you one of them? This post will help you solve this problem.
Notepad++ is an excellent text editor for developing and running code due to its compatibility with several programming languages, such as Java, Python, etc. In addition to syntax highlighting, this editor provides a few other capabilities that are very helpful for programmers.
Method 1: Utilizing Option Run In Notepad++ To Run Python
You must select the option Run in the menu of the Notepad++ editor before running your Python file. Then, choose Run… (the first one in the dropdown menu).
You will see a new window appear on your screen as below. As an alternative, you may also access this window by using the key F5 on your keyboard.
Enter the following command in the dialog box The Program to Run, and hit Run.
C:\Python39\python.exe -i "$(FULL_CURRENT_PATH)"
The C:\Python39\python.exe parameter specifies Python’s installation location on the computer. Meanwhile, the final component is the path to the file you wish to launch. Keep in mind that you do not need to specify the path of the file; Python will figure it out for you using $(FULL_CURRENT_PATH).
Notice that the option –i is uncompelled in this case. Utilize this option if you want the command line window to remain active even after the file has finished running. It will then launch a command line window where your file will be run, as seen in the illustration below.
Method 2: Utilizing PyNPP Plugin In Notepad++ To Run Python
Additionally, Python applications in text editor Notepad++ can be launched via the PyNPP plugin. To begin, navigate to Plugins and choose Plugins Admin… in the dropdown bar.
As displayed below, a dialog window will appear. Enter the plugin PyNPP into the search box. Here, you will find a list with the name of each plugin and its version number. Check the box next to the name of the plugin PyNPP.
Next, select the button Install located in the dialog box’s upper right corner.
When a new box appears, continue to select Yes. By doing this, you can install the plugin PyNPP and reopen the Notepad++ text editor.
After successfully installing the plugin, you may now open the file by simultaneously hitting the Alt, Shift, and F5 buttons on the keyboard. As you do this, a new terminal box will open and display the file’s output as displayed below.
The Bottom Line
Now you know how to utilize Notepad++ to run Python. As you can see, the procedure is quite simple to execute; continue honing your skills until you are proficient in these methods.
Bonus: Here are some more tutorials on how to parallel for loop and simulate the which command for you to check out to gain more skills in Python.
Run Python in Notepad++
- Run Python File Using Run Option in Notepad++
- Run Python File Using PyNPP Plugin in Notepad++
As we all know, Notepad++ is a great editor. Many people prefer this text editor for writing and executing their code. It supports various programming languages, including the Python programming language. But many people face challenges or get stuck while running the Python file inside the notepad++ text editor. So, Let’s see how to execute or run a Python file inside the notepad++.
Run Python File Using Run Option in Notepad++
To run the Python file from the notepad++ text editor, you have to click on the Run option from the menu and then choose the first option — Run. from the dropdown menu.
It will open a new window on the screen, as shown below. Alternatively, You can also press the F5 key on the keyboard to open this window.
In the The Program to Run dialog box, enter the below command and click on Run .
C:\Python39\python.exe -i "$(FULL_CURRENT_PATH)"
The First parameter, C:\Python39\python.exe , is the location where Python is installed on the system. And the last parameter is the current path of the file which you want to run. You don’t have to specify the file path; Python will automatically detect the file path you are currently running with $(FULL_CURRENT_PATH) .
Here, -i is optional. If you want to keep the command line window open even after the execution of the file, then use this option.
After that, it will open a command line window inside which your file will be executed, as shown below.
Run Python File Using PyNPP Plugin in Notepad++
You can also run Python programs with the help of a plugin provided by a notepad++ text editor called PyNPP. For that, first, go to Plugins and select Plugins Admin. from the dropdown.
A dialog box will open, as shown below. Now in the search box, search for PyNPP plugin. Below you will see a list that will contain the plugin’s name and their version number. Just check the checkbox beside the PyNPP plugin name.
After that, click on the Install button present at the top right corner of the dialog box.
Now another dialog box will open up, so click Yes . This will restart the notepad++ editor and install the PyNPP plugin.
Now that we have successfully installed the plugin, we can run the file by pressing the Alt + Shift + F5 keys simultaneously on the keyboard. As soon as you press these buttons, a terminal window will be opened up, which will show you the output of the file as shown below.
Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.
Related Article — Python Run
Notepad++ Run Python Script: A Completed Guide – Python Tutorial
Notepad++ is a powerful editor, it is also a python editor for python programmers. In this tutorial, we will introduce how to edit and run python script by it.
Preliminary
You should install Notepad++ and python first.
To install python, you can read this tutorial:
Create a python file
You should open notepad++ and create a python script, here is an example:
import time text = 'this is https://www.tutorialexample.com' print(text) time.sleep(5)
Then we will introduce how to run this python script by notepad++.
Press Run or F5 on the notepad++
You can start to clicking run or press F5 to start to run python script.
Set the path of python script
As to our python environment, the absolute path of python.exe is:
Then you can add this string in the input box below:
C:\Users\fly165\.conda\envs\py3.6\python.exe $(FULL_CURRENT_PATH)
Where $(FULL_CURRENT_PATH) represents the current file, which means if you want to run a python script, you should foucs on this file.
Moreover, if the type of current file is not .py , you will can not run it.
Save command
We can save our command that runs python script with the name: Run Python .
Then you can Press Alt+F7 to run python script on notepad++.
In this tutorial, the resutl of python script is: