Find and replace in project
You can search for a text string within a project, use different scopes to narrow your search process, exclude certain items from your search, find usages and occurrences.
Find the search string in a project

- Go to Edit | Find | Find in Files Control+Shift+F .
- In the search field, type your search string. Alternatively, in the editor, highlight the string you want to find and press Control+Shift+F . PyCharm places the highlighted string into the search field. To see a list of your previous searches, press Alt+ArrowDown . If you need, specify the additional options. PyCharm lists the search strings and the files that contain them. If the search string is found several times on the same line of code, PyCharm merges the results in one line. To do a multi-line search, click the icon to enter a new line, and press Control+Alt+ArrowDown / Control+Alt+ArrowUp to browse through occurrences.
- Check the results in the preview area of the dialog where you can replace the search string or select another string, press Control+Shift+F again and start a new search.
- To see the list of occurrences in a separate tool window, click Open in Find Window . Use this window and its options to group the results, preview them, and work with them further. If you want to see each new search result in a separate tab in the Find tool window, click on the bottom of the Find in Files dialog and select the Open Results in New Tab checkbox.
Copy paths or references of the found files
- In the list of search results, right-click the result for which you want to copy a path and click Copy/Reference .
- In the Copy window, select the path or reference you need.
Narrow your search
You can use different options in the Find in Files dialog to adjust your search process.

- Select options such as Words () or Match case () to find the exact word in a project or match the letter case.
- With selected, PyCharm automatically escapes special regex symbols with backslash \ when you search for a text string that contains them. Keep in mind that if you copy ( Control+C ) the string first and then paste ( Control+V ) it in the search field, the regex symbols will not be taken into account. For more information about regex , refer to the search with regex documentation.
- Click the icon to filter your search. For example, you can filter the search to omit comments or search only in comments instead.
- Select one of the displayed options such as Module or Directory to limit your search. Moreover, you can select the Scope option that offers you a list of predefined scopes for your search. For example, you can limit your search only to the open files in your project. If you work without tabs, the scope Recently Viewed Files or Recently Changed Files option might become quite useful. You can also create your own custom scope, click the Browse icon () to open the Scopes dialog.
Search in the specific file types
Use the File Mask option to narrow your search to a specific file type. You can select the existing file type from the list, add a new file type, or add an additional file mask syntax to search for file types with certain patterns.

- Go to Edit | Find | Find in Files Control+Shift+F .
- In the Find in Files dialog, select the File Mask checkbox and from the list of file types, select the one you need. PyCharm limits its search to the specified type.
- If you don’t find the file type you need in the list, enter your file type in the File Mask field. Besides * , other wildcards are supported. If necessary, specify several file types using commas as separators. You can manually add a file mask in the search field. If necessary, specify several file types separating them with commas.
Search for usages in a project
You can search for usages of a symbol in your whole project or in a scope that you set.
Click to open the Find Usages dialog.
- Go to Edit | Find | Find in Files Control+Shift+F .
- Select the symbol for which you want to find usages. Note that you can extend your search to file usages as well.
- In the main menu, go to Edit | Find | Find Usages Alt+F7 . To see usages of the selected symbol within a file, right-click the context menu in your file and select Find Usages Control+F7 .
- Check the results in the Find tool window. Click to open the Find Usages dialog.
You can also pull out the results from the previous Find Usages actions. Go to Edit | Find | Recent Find Usages and the usage query. While in the Find tool window, you can use the Preview area to check the places where the usages were found, to see a call hierarchy for methods, data flow for fields, and so on.
If PyCharm doesn’t return any results, it will display a message suggesting to opt for more options. You can follow the link or press Control+Alt+Shift+F7 to open the Find Usages dialog where you can set a new scope for your search.
For example, you can set your search scope to production files only or to only open files. To set a custom scope, click . - When you are done setting a new scope, click Find .
If you want PyCharm to show you usages of the selected symbol in the separate window, press Control+Alt+F7 . You can use this window for quick navigation.

Press the same shortcut again to see the usages in the default scope.
To view the results of previous Find Usages actions, go to Edit | Find | Recent Find Usages in the main menu, and then select the usage query.
Disable automatic highlighting of usages
When you place the caret at a symbol, the IDE highlights all usages of this symbol in the current file. Use the F3 and Shift+F3 shortcuts to navigate between highlighted symbols.
In the Power Save Mode, highlighting of usages is disabled.
If necessary, you can disable the automatic highlighting.
- In the Settings dialog ( Control+Alt+S ), go to Editor | General , and clear the Highlight usages of element at caret checkbox.
When the automatic highlighting is disabled, place the caret at the necessary symbol and press Control+Shift+F7 . This will highlight all usages of the symbol in the current file.
Replace the search string in a project

- Press Control+Shift+R ( Edit | Find | Replace in Path ) to open the Replace in Path dialog.
- In the top field, enter your search string. In the bottom field, enter your replacement string. For example, if you want to replace a variable name with a new name for a large project, use the Replace in path instead of the Rename refactoring since your variable can appear in the config files as well.
- Click one of the available Replace commands.
PyCharm
PyCharm (https://www.jetbrains.com/ru-ru/pycharm/) — интегрированная среда разработки для языка программирования Python. Предоставляет средства для анализа кода, графический отладчик, инструмент для запуска юнит-тестов и поддерживает веб-разработку на Django.
- 1 Установка из Flatpak
- 1.1 Из Центра приложений
- 1.2 В командной строке
- 2.1 Из Центра программ Discover
- 2.2 В командной строке
Установка из Flatpak
После установки PyCharm из Flatpak программа появится в «Меню запуска приложений» автоматически.
Внимание! Для возможности установки приложений из репозитория flathub всем пользователям, следует разрешить для всех доступ к инструментам монтирования файловых систем fuse:
# control fusermount publicИз Центра приложений
Центр приложений позволяет устанавливать и удалять программы из репозиториев Альт и сторонних приложений в формате Flatpak.

- Запустить «Центр приложений» («Меню запуска приложений» → «Системные» → «Центр приложений»).
- В категории «Инструменты разработки» выбрать PyCharm-Community.
- Нажать кнопку «Установить»:
В командной строке
Обновить данные в репозитории:
$ flatpak update
$ flatpak search pycharm Имя ID Приложения Версия Ветка Удаленные репозитории PyCharm-Community com.jetbrains.PyCharm-Community 2022.1.2 stable flathub Python 2.7 com.jetbrains.PyCharm.Extensions.Python2-7 2.7.18 20.08 flathub PyCharm-Professional com.jetbrains.PyCharm-Professional 2022.1.2 stable flathub
$ flatpak install flathub PyCharm-Community
где flathub — название репозитория.
$ flatpak run com.jetbrains.PyCharm-Community
Установка SNAP-приложения
После установки SNAP-приложения PyCharm программа появится в «Меню запуска приложений» автоматически.
Внимание! PyCharm устанавливается с использованием «классического» ограничения: пакет фактически не использует песочницу и может вносить изменения в остальную часть системы.
Чтобы выполнить установку с использованием классического ограничения, в системе должен существовать каталог /snap . Если его нет, можно создать его как символическую ссылку, которая указывает на каталог /var/lib/snapd/snap :
# ln -s /var/lib/snapd/snap /snapИз Центра программ Discover

- Запустить «Центр приложений» («Меню запуска приложений» → «Система» → «Discover (Центр программ)»).
- Выполнить поиск по ключевому слову «pycharm» и выбрать PyCharm-Community (snap).
- Нажать кнопку «Установить»:
В командной строке
$ snap find pycharm Name Version Publisher Notes Summary pycharm-community 2022.1.2 jetbrains✓ classic PyCharm Community Edition pycharm-professional 2022.1.2 jetbrains✓ classic PyCharm Professional Edition pycharm-educational 2022.1.1 jetbrains✓ classic Easy and Professional Tool to Learn & Teach Programming with Python
$ snap install --classic pycharm-community 2022-06-03T09:44:54+02:00 INFO Waiting for automatic snapd restart. pycharm-community 2022.1.2 from jetbrains✓ installed
$ snap run pycharm-community
Установка из tar-архива
PyCharm можно установить, загрузив архив с сайта разработчика (https://www.jetbrains.com/ru-ru/pycharm/):

- Загрузить PyCharm с сайта разработчика:
- Переместить загруженный архив в выбранный каталог (у пользователя должны быть права доступа RW для этого каталога).
- Распаковать архив, выполнив следующую команду из каталога с архивом:
$ tar -xzf pycharm-2022.1.2.tar.gz
$ pycharm-community-2022.1.1/bin/pycharm.sh
Примечание: Пункты 1-3 можно заменить одной командой. Следующая команда загрузит архив pycharm-2022.1.2.tar.gz с сайта разработчика и распакует его в каталог, из которой она была вызвана:
$ curl -L https://download.jetbrains.com/python/pycharm-community-2022.1.1.tar.gz | tar -xvzЧтобы не вызывать скрипт, указывая каждый раз его полный путь, можно создать ссылку, которая будет указывать на него:
$ ln -s ~/pycharm/pycharm-community-2022.1.2/bin/pycharm.sh ~/bin/PyCharm
Теперь можно запустить PyCharm, выполнив команду PyCharm .
Примечание: Ссылку нужно создавать внутри любого каталога, который являются частью PATH пользователя:
$ echo $PATH;
Для добавления значка запуска PyCharm в «Меню запуска приложений» следует создать файл ~/.local/share/applications/pycharm.desktop со следующим содержимым:
[Desktop Entry] Version=1.0 Type=Application Name=PyCharm Community Edition Icon=/home/user/pycharm/pycharm-community-2022.1.2/bin/pycharm.png Exec=/home/user/pycharm/pycharm-community-2022.1.2/bin/pycharm.sh Comment=Python IDE for Professional Developers Categories=Development;IDE; Terminal=false StartupWMClass=jetbrains-pycharm-ce StartupNotify=true
- Icon — полный путь к значку;
- Exec — полный путь к скрипту pycharm.sh (здесь можно также указать PyCharm , если создавалась ссылка).
PyCharm появится в «Меню запуска приложений»:
demiurg906 / IDEA_shortcuts.md
Используются для генерации кода непосредственно при написании кода. Вызываются при выборе нужного template’а в completion pop-up. Полезные темплейты:
- psvm — public static void main(String[] args) <>
- psf — public static final
- sout — System.out.println();
- serr — System.err.println();
- thr — throw new
- .par — обернуть в скобки
- 1 + 1.par -> (1 + 1)
List list = . ; // list.for for (String e : list) < > // list.fori for (int i = 0; i < list.size(); i++) < > // list.forr for (int i = list.size() - 1; i >= 0; i--) < >- ctrl-alt-V — вынести выделенное выражение в переменную
- ctrl-alt-C — вынести выделенное выражение в константу
- ctrl-alt-M — вынести выделенный код в отдельный метод
- ctrl-shift-№ ( № = 0..9 ) — создать закладку с номером №
- ctrl-№ ( № = 0..9 ) — перейти к закладке с номером №
- ctrl-F11 — создать закладку
- F11 — перейти к закладке
- F5 — скопировать файл
- F6 — перенести файл
- ctrl-shift-F/R — найти/заменить текст во всех файлах проекта
- ctrl-D — сравнить два выделенных файла
- by default шортката нет, но я крайне рекомендую настроить — создать новый файл/директорию в выбранном месте
- ctrl-D — смотреть изменения
- ctrl-F7 — перейти к следующему изменению
- ctrl-shift-F7 — перейти к предыдущему изменению
- alt-shift-M — перенести файлы в другой Changelist
- alt-Space — сделать выделенный Changelist активным
- ctrl-alt-P — сгрупировать изменённые файлы по директории
- ctrl-F — поиск коммита с указанным хешом
- ctrl-shift-F10 — запустить main функцию/тест в текущем файле
- shift-F10 — запустить последнюю запущенную run конфигурацию
- alt-shift-F10 — запустить одну из доступных run конфигураций
- всё то же самое, но с F9 — запустить в режиме дебага
- ctrl-ctrl — запустить что-нибудь из последнего
- ctrl-F8 — поставить breakpoint на текущей строчке
- F9 — выполнить до следующего breakpoint’а
- alt-F9 — выполнить до курсора
- F8 — выполнить до следующей строчки
- F7 — зайти внутрь вызова функции
- shift-F7 — выбрать вызов функции, в который надо зайти
- shift-F8 — выйти из текущей функции
- alt-F8 — выполнить произвольное выражение
- Insert — добавить в список watches новое выражение
Подскажите как PyCharm изменить имя переменой сразу в нескольких местах?

Я хочу добавить self. ко все переменным man_calories, но прописывать для каждой это долго, можно ли как то изменить за раз все сразу переменны man_calories?
Отслеживать
26.2k 7 7 золотых знаков 31 31 серебряный знак 48 48 бронзовых знаков
задан 11 ноя 2021 в 6:41
310 1 1 золотой знак 3 3 серебряных знака 11 11 бронзовых знаков3 ответа 3
Сортировка: Сброс на вариант по умолчанию
Shift + F6 (курсор должен быть на переменной)
или Top Menu -> Refactor -> Rename
Отслеживать
ответ дан 11 ноя 2021 в 7:27
31 3 3 бронзовых знака
Shift + f8 не сработал
11 ноя 2021 в 7:49Для изменения связанных переменных выделите необходимую переменную и нажмите ctrl+shift+f6
Отслеживать
ответ дан 11 ноя 2021 в 7:22
Ян Морозов Ян Морозов
119 1 1 серебряный знак 5 5 бронзовых знаковЕсли вы не меняли настроек по умолчанию, то:
- Найти и заменить в проекте ==> Ctrl + Shift + R
- Найти и заменить в локальном файле ==> Ctrl + R
Иногда вместо R нужно использовать H или F
Отслеживать
ответ дан 11 ноя 2021 в 6:54
481 2 2 серебряных знака 9 9 бронзовых знаковЭто можно конечно, у меня есть в файле еще переменная woman_calories и он изменяет ее тоже, а мне этого не нужно
11 ноя 2021 в 7:06
@Tesla Вы заменяете man_calories на self.man_calories? Если да, то woman_calories не должно затрагиваться)
11 ноя 2021 в 7:10
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2024 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2024.1.8.3130
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.