Как сделать pycharm поверх всех окон

Обновлено: 27.03.2024

The PyCharm editor is the main part of the IDE that you use to create, read and modify code.

The editor consists of the following areas:

The scrollbar shows errors and warnings in the current file.

Breadcrumbs help you navigate inside the code in the current file.

The gutter shows line numbers and annotations.

Tabs show the names of the currently opened files.

Navigation

You can use various shortcuts to switch between the editor and different tool windows, change the editor size, switch focus, or return to the original layout.

Maximize editor pane

In the editor, press Ctrl+Shift+F12 . PyCharm hides all windows except the active editor.

You can maximize a split screen as well. In this case the active screen is maximized and other screens are moved aside.

Switch the focus from a window to the editor

Press Escape . PyCharm moves the focus from any window to the active editor.

Return to the editor from the command-line terminal

Press Alt+F12 . PyCharm closes the terminal window.

If you need to keep the terminal window open when you switch back to the active editor, press Ctrl+Tab .

Return to the default layout

To save the current layout as the default, from the main menu select Window | Store Current Layout as Default . You can use the same shortcut Shift+F12 to restore the saved layout.

Jump to the last active window

Use the switcher for navigation

To jump between the opened files and tool windows with the switcher, press Ctrl+Tab .

Keep Ctrl pressed to leave the switcher popup open.

Press Tab to move between elements. Press Backspace to remove the selected file from the list and close it in the editor.

Change the IDE appearance

You can switch between schemes, keymaps, or viewing modes.

In the Switch menu, select the option you need and press Enter . Use the same shortcut Ctrl+` to undo your changes.

You can also find and adjust the color scheme settings including the high contrast color scheme for people with eyesight deficiency on the Editor | Color Scheme page and the keymap settings on the Keymap page of the Settings/Preferences dialog ( Ctrl+Alt+S ).

Jump to the navigation bar

Press Alt + Home .

Scrollbar

When you work with code in the editor, PyCharm displays code analysis results that include errors and warnings on the scrollbar. You can check whether your code has issues and quickly navigate to them.

The top of the scrollbar has the Inspections widget that gives you a brief summary of the code problems. Click the widget get more information on each detected problem in the Problems tool window.

Code analysis summary for a file

The stripes on the scrollbar indicate places where PyCharm found a problem. Hover over a stripe to see a tooltip describing the problem or click the stripe for a quick navigation.

It is normal to see many stripes while you are working on a file. Many of these errors, warnings, and suggestions are eventually resolved as you complete the code. Should any errors remain when you feel your code is complete we recommend that you explore and resolve them before compiling your project.

The different colors of stripes indicate severity of the problems from an error marked in red to a TODO comment marked in blue, but you can change the displayed colors if you need. For more information, refer to Change inspection severity.

Editor tabs

You can close, hide, and detach editor tabs. Every time you open a file for editing, a tab with its name is added next to the active editor tab.

From the main menu, select Window | Editor Tabs to see what additional actions you can perform with the editor tabs. For example, Close Tabs to the Left or Close Tabs to the Right .

You can use the tab's context menu for the same purpose or located in the editor.

To configure the settings for editor tabs, use the Editor | General | Editor Tabs page of the Settings/Preferences dialog ( Ctrl+Alt+S ). Alternatively, right-click a tab and select Configure Editor Tabs from the list of options.

Open or close tabs

To close all opened tabs, select Window | Editor Tabs | Close All Tabs from the main menu.

To close all inactive tabs, press Alt and click on the active tab. In this case, only the active tab stays open.

To close all inactive tabs except the active one and the pinned tabs, right-click any tab and select Close Other Tabs .

To close only the active tab, press Ctrl+F4 . You can also click the mouse's wheel button anywhere on a tab to close it.

To reopen the closed tab, right-click any tab, and from the context menu, select Reopen Closed Tab .

To open a new tab at the end of the already opened one, select the Open new tabs at the end in the tab settings.

Copy path or filename

Right-click the tab.

From the list that opens, select Copy Path/Reference .

From the list that opens, select your copy option.

Copy path

PyCharm copies the item to the clipboard and you can paste it ( Ctrl+V ) wherever you need.

Move, remove, or sort tabs

To move or remove the icon on a tab, in the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General | Editor Tabs and select the appropriate option in the Close button position field.

To place the editor tabs in a different part of the editor frame or hide the tabs, right-click a tab and select Configure Editor Tabs to open the Editor Tabs settings. In the Appearance section, in the Tab placement list, select the appropriate option.

To access the Editor Tabs settings when all tabs are hidden, select Window | Editor Tabs | Configure Editor Tabs from the main menu.

To sort the editor tabs alphabetically, right-click a tab and select Configure Editor Tabs to open the Editor Tabs settings. In the Tab order section, select Sort tabs alphabetically .

Pin or unpin a tab

You can pin an active tab in the editor so that it will stay open when the tab limit is reached or when you use the Close Other Tabs command.

To pin or unpin an active tab, right-click it and select Pin Tab or Unpin Tab from the context menu.

To close all tabs, but the pinned ones, right-click any tab and select Close All but Pinned .

To assign a keyboard shortcut for the Pin Tab action, in the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Keymap , find the Pin Active Tab action, right-click it, select Add Keyboard Shortcut , and press the key combination you want to use.

Detach a tab

When you detach a tab, the tab opens in a separated window and the window becomes reserved for the detached tab. If you try to detach another tab from the main frame, it will be opened in the new window.

To detach an active tab, press Shift+F4 .

Drag the tab you need outside of the main window and drag the tab back to attach it.

You can also use Alt+mouse for the same action.

In the Project tool window, select a file you want to detach and press Shift+Enter .

Switch between tabs

To move between tabs, press Alt+Right or Alt+Left .

You can also switch between recently viewed tabs or files.

In the editor, press Ctrl+Tab . Keep pressing Ctrl for the Switcher window to stay open. Use Tab to switch between tabs and other files.

Assign a shortcut for the opened tab

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Keymap .

In the list of directories, click the Other directory and from the list of tabs, select the one for which you need to add a shortcut. The limit of tabs to which you can assign shortcuts is 9.

Change the default tab limit

PyCharm limits number of tabs that you can open in the editor simultaneously (the default tab limit is 10).

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General | Editor Tabs .

In the Tab closing policy section, adjust the settings according to your preferences and click OK .

If the tab limit equals to 1, the tabs in the editor will be disabled. If you want the editor to never close the tabs, type some unreachable number.

Open files in the preview tab

The preview tab allows you to view files in a single tab one by one without opening each file in a new tab. This is helpful if you need to look through several files without exceeding the tab limit.

In the Project tool window Alt+1 , click and select the Enable Preview Tab option.

You can also enable the preview tab in Settings/Preferences | General | Editor Tabs | Opening Policy .

In the Project tool window, select a file that is not already open in any other tab.

The name of the file is written in italic to indicate the preview mode. Any other file that you select will replace the previous one in the preview tab.

Start editing the file to exit the preview mode and change it to a regular tab.

The preview tab

Note that when the preview tab is enabled, the Open Files with Single Click option is ignored. Double-click a file to open it in a regular tab.

Hide editor tabs if there is no more space

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General | Editor Tabs .

Select the Hide tabs if there is no space option. Extra tabs will be placed in the list located in the upper right part of the editor.

Change the font size in tabs

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Appearance & Behavior | Appearance .

In the Size field, specify the font size and click OK to save the changes.

Keep in mind that the font size will change not only for tabs, but for tool windows as well.

Split screen

PyCharm offers various actions that you can invoke from main or context menu, editor, or the project tool window to split the editor screen.

In the editor, right-click the desired editor tab and select how you want to split the editor window ( Split Right or Split Down ). PyCharm creates a split view of the editor and places it according to your selection.

As an alternative, from the main menu, select Window | Editor Tabs and the Split and Move Right or Split and Move Down option.

You can drag a tab vertically or horizontally in order to split the editor, and drag the tab back to unsplit the screen.

You can open a file in the editor in the right split.

In the Project tool window, right-click a file and select Open in Right Split from the context menu. PyCharm will open a file in the split on the right of the editor.

If there are two splits and focus is in the left split, the file will be opened in the existing right split. If the focus is in the right split, the file will be opened in the next right split.

You can move files between split screens. Right-click the needed file tab in the editor and from the context menu select Move To Opposite Group or Open In Opposite Group .

You can close all the open tool windows at once and thus enlarge the split screens. Position the caret in an editor tab and press Ctrl+Shift+F12 or just double-click the tab. PyCharm hides all the open tool windows so all the space is shared by split screens.

To unsplit the screen, from the context menu, select Unsplit or Unsplit All to unsplit all the split frames.

Move the split screen

Place the caret inside the desired split frame.

From the main menu, select Window | Editor Tabs .

From the list of options, select one of the following options:

Stretch Editor to Top

Stretch Editor to Left

Stretch Editor to Bottom

Stretch Editor to Right

You can assign a shortcut to each option and use a keyboard to stretch the split frame.

To move between the split frames which you've created, from the main menu, select Window | Editor Tabs . From the list of options select Goto Next Splitter Alt+Tab or Goto Previous Splitter Alt+Shift+Tab respectively.

Quick popups

View quick definition of a symbol (tag, class, method/function, field, and so on.)

PyCharm displays the information in a popup. If you need, click the icon to open the Find tool window with the item's definition and its usages.

View quick documentation for a code element or a file.

PyCharm displays a popup with the appropriate information.

You can press Ctrl+Q twice to open the popup in the Documentation tool window. (Press same shortcut to switch back to the popup).

If you need to change the font size of the text displayed in the popup window, click the icon and in the window that opens, change the font size according to your preferences.

For code elements you can also view an external documentation while in the quick documentation popup. Click or press Shift+F1 .

External Python documentation becomes available when you properly configure it in the Settings/Preferences | Tools | Python External Documentation.

If you invoke the quick documentation popup when you look for a class Ctrl+N , you can look up the documentation on any class displayed in the list. To switch focus to the popup, press the same shortcut.

View the context information .

The action shows the current method or class declaration when it is not visible.

View a description of the error or warning at the caret.

Click the code analysis marker to see the list of found errors. Use F2 or Shift+F2 to navigate to next or previous error.

Copy tooltip text to the clipboard.

Hold Alt (on Linux, hold Ctrl+Alt ) and click the tooltip

View all usages for code element .

To control the usages highlighting, select or clear the Highlight usages on element at caret option, in Settings/Preferences | Editor | General (the Highlight on Caret Movement area).

If you turn on the Power Save mode ( File | Power Save Mode ), the usages are not highlighted.

Useful editor configurations

You can use the Settings/Preferences dialog ( Ctrl+Alt+S ) to customize the editor's behavior.

Editor settings

Check the following popular configurations:

Configure code formatting

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | Code Style .

From the list of languages select the appropriate one and on the language page, configure settings for tabs and indents, spaces, wrapping and braces, hard and soft margins, and so on.

Configure fonts, size, and font ligatures

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | Font .

If you, for example, have previously saved Color Scheme Font settings, the main settings become overridden. The link with the appropriate notification will appear on the Font page.

Change the font size in the editor

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General ( Mouse Control section).

Select the Change font size with Ctrl+Mouse Wheel in option.

Return to the editor, press and hold Ctrl , and using the mouse wheel, adjust the font size.

You can configure the editor size on the Font page of the editor settings.

Configure the color scheme settings for different languages and frameworks

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | Color Scheme .

Open the Color Scheme node and select the needed language or framework. You can also select the General option from the node's list to configure the color scheme settings for general items such as code, editor, errors and warnings, popups and hints, search results, and so on.

Configure code completion options

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General | Code Completion . Here you can configure the case sensitive completion, auto-display options, code sorting, and so on.

Configure the caret placement

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General . In the Virtual Space section, you can configure the caret placement options.

Select the Allow placement of caret after end of line option to place the caret at the next line in the same position as the end of the previous line. If this option is cleared, the caret at the next line is placed at the end of the actual line.

Select the Allow placement of caret inside tabs option to help you move the caret up or down inside the file while keeping it in the same position.

Configure the behavior of trailing spaces on save

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General . In the Other section, you can configure options for trailing spaces.

For example, when you save your code either manually or automatically and want to preserve trailing spaces on the caret line regardless of what option is selected in the Strip trailing spaces on save list, select the Always keep trailing spaces on caret line option.

Configure the editor appearance options

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General | Appearance .

For example, you can configure showing the hard wrap guide, or showing parameter hints.

Manage the appearance for long lines

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General .

In the Soft Wraps section, specify the appropriate options.

For example, you can specify file types to which you want to apply soft wraps. It might be helpful when you write documentation in markdown files.

Configure smart keys

You can configure a certain behavior for different basic editor actions depending on the language you use.

In the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | General | Smart keys .

For example, for Java, SQL or Python, you can select the Jump outside closing bracket/quote with Tab option to enable navigation outside the closing brackets or quotes with Tab when you type your code.

Язык программирования Python считается достаточно простым. На нем легче и быстрее пишутся программы, по сравнению с компилируемыми языками программирования. Для Python существует множество библиотек, позволяющих решать практически любые задачи. Есть, конечно, и минусы и другие нюансы, но это отдельная тема.

Статья начинается с базовых вещей: с установки Python 3, инструментов разработки Pip и Virtualenv и среды разработки PyCharm в Windows и в Ubuntu. Для многих это не представляет трудностей и возможно, что уже всё установлено.

После чего будет то, ради чего задумывалась статья, я покажу как в PyCharm создавать и использовать виртуальные окружения и устанавливать в них библиотеки с помощью Pip.

Установка Python и Pip

Pip является менеджером пакетов для Python. Именно с помощью него обычно устанавливаются модули/библиотеки для разработки в виде пакетов. В Windows Pip можно установить через стандартный установщик Python. В Ubuntu Pip ставится отдельно.

Установка Python и Pip в Windows

Для windows заходим на официальную страницу загрузки, где затем переходим на страницу загрузки определенной версии Python. У меня используется Python 3.6.8, из-за того, что LLVM 9 требует установленного Python 3.6.

Далее в таблице с файлами выбираем "Windows x86-64 executable installer" для 64-битной системы или "Windows x86 executable installer" для 32-битной. И запускаем скачанный установщик, например, для версии Python 3.8.1 он называется python-3.8.1-amd64.exe .

Во время установки ставим галочку возле Add Python 3.x to PATH и нажимаем Install Now:

Установка Python 3 в Windows 10

Установка Python и Pip в Ubuntu

В Ubuntu установить Python 3 можно через терминал. Запускаем его и вводим команду установки. Вторая команда выводит версию Python.

Далее устанавливаем Pip и обновляем его. После обновления необходимо перезапустить текущую сессию (или перезагрузить компьютер), иначе возникнет ошибка во время вызова Pip.

Основные команды Pip

Рассмотрим основные команды при работе с Pip в командой строке Windows и в терминале Ubuntu.

Команда Описание
pip help Справка по командам
pip search package_name Поиск пакета
pip show package_name Информация об пакете
pip install package_name Установка пакета(ов)
pip uninstall package_name Удаление пакета(ов)
pip list Список установленных пакетов
pip install -U Обновление пакета(ов)

Если виртуальные окружения не используются, то во время установки пакета(ов) полезно использовать дополнительно ключ --user , устанавливая пакет(ы) локально только для текущего пользователя.

Установка VirtualEnv и VirtualEnvWrapper

VirtualEnv используется для создания виртуальных окружений для Python программ. Это необходимо для избежания конфликтов, позволяя установить одну версию библиотеки для одной программы, и другу для второй. Всё удобство использования VirtualEnv постигается на практике.

Установка VirtualEnv и VirtualEnvWrapper в Windows

В командной строке выполняем команды:

Установка VirtualEnv и VirtualEnvWrapper в Ubuntu

Для Ubuntu команда установки будет следующей:

После которой в конец ~/.bashrc добавляем:

Работа с виртуальным окружением VirtualEnv

Рассмотрим основные команды при работе с VirtualEnv в командой строке Windows и в терминале Ubuntu.

Команда Описание
mkvirtualenv env-name Создаем новое окружение
workon Смотрим список окружений
workon env-name Меняем окружение
deactivate Выходим из окружения
rmvirtualenv env-name Удаляем окружение

Находясь в одном из окружений, можно ставить пакеты через Pip, как обычно и нет необходимости добавлять ключ --user :

Для Windows можно указать в переменных среды WORKON_HOME для переопределения пути, где хранятся виртуальные окружения. По умолчанию, используется путь %USERPROFILE%\Envs .

Установка PyCharm

PyCharm — интегрированная среда разработки для языка программирования Python. Обладает всеми базовыми вещами необходимых для разработки. В нашем случае огромное значение имеет хорошее взаимодействие PyCharm с VirtualEnv и Pip, чем мы и будем пользоваться.

Установка PyCharm в Windows

Скачиваем установщик PyCharm Community для Windows с официального сайта JetBrains. Если умеете проверять контрольные суммы у скаченных файлов, то не забываем это сделать.

В самой установке ничего особенного нету. По сути только нажимаем на кнопки next, и в завершение на кнопку Install. Единственно, можно убрать версию из имени папки установки, т.к. PyCharm постоянно обновляется и указанная версия в будущем станет не правильной.

Установка PyCharm в Ubuntu

Скачиваем установщик PyCharm Community для Linux с официального сайта JetBrains. Очень хорошей практикой является проверка контрольных сумм, так что если умеете, не ленитесь с проверкой.

Распаковываем архив с PyCharm и переименовываем папку с программой в pycharm-community , убрав версию из названия.

Теперь в директории ~/.local (Ctrl + H — Показ скрытый файлов), создаем папку opt , куда и перемещаем pycharm-community . В результате по пути /.local/opt/pycharm-community должны размещаться папки bin , help и т.д. Таким образом PyCharm будет находится в своём скромном месте и никому не будет мешать.

Далее выполняем команды в терминале:

Производим установку. И очень важно в конце не забыть создать desktop файл для запуска PyCharm. Для этого в Окне приветствия в нижнем правом углу нажимаем на Configure → Create Desktop Entry.

Создание desktop файла

Установка PyCharm в Ubuntu из snap-пакета

PyCharm теперь можно устанавливать из snap-пакета. Если вы используете Ubuntu 16.04 или более позднюю версию, можете установить PyCharm из командной строки.

Использование VirtualEnv и Pip в PyCharm

Поддержка Pip и Virtualenv в PyCharm появилась уже довольно давно. Иногда конечно возникают проблемы, но взаимодействие работает в основном стабильно.

Рассмотрим два варианта работы с виртуальными окружениями:

  1. Создаём проект со своим собственным виртуальным окружением, куда затем будут устанавливаться необходимые библиотеки;
  2. Предварительно создаём виртуальное окружение, куда установим нужные библиотеки. И затем при создании проекта в PyCharm можно будет его выбирать, т.е. использовать для нескольких проектов.

Первый пример: использование собственного виртуального окружения для проекта

Создадим программу, генерирующую изображение с тремя графиками нормального распределения Гаусса Для этого будут использоваться библиотеки matplotlib и numpy, которые будут установлены в специальное созданное виртуальное окружение для программы.

Запускаем PyCharm и окне приветствия выбираем Create New Project.

В мастере создания проекта, указываем в поле Location путь расположения создаваемого проекта. Имя конечной директории также является именем проекта. В примере директория называется 'first_program'.

Далее разворачиваем параметры окружения, щелкая по Project Interpreter. И выбираем New environment using Virtualenv. Путь расположения окружения генерируется автоматически. В Windows можно поменять в пути папку venv на Envs , чтобы команда workon находила создаваемые в PyCharm окружения. Ставить дополнительно галочки — нет необходимости. И нажимаем на Create.

Настройка первой программы в PyCharm

Теперь установим библиотеки, которые будем использовать в программе. С помощью главного меню переходим в настройки File → Settings. Где переходим в Project: project_name → Project Interpreter.

Чистое окружение у проекта

Здесь мы видим таблицу со списком установленных пакетов. В начале установлено только два пакета: pip и setuptools.

Справа от таблицы имеется панель управления с четырьмя кнопками:

  • Кнопка с плюсом добавляет пакет в окружение;
  • Кнопка с минусом удаляет пакет из окружения;
  • Кнопка с треугольником обновляет пакет;
  • Кнопка с глазом включает отображение ранних релизов для пакетов.

Для добавления (установки) библиотеки в окружение нажимаем на плюс. В поле поиска вводим название библиотеки. В данном примере будем устанавливать matplotlib. Дополнительно, через Specify version можно указать версию устанавливаемого пакета и через Options указать параметры. Сейчас для matplotlib нет необходимости в дополнительных параметрах. Для установки нажимаем Install Package.

Установка библиотеки matplotlib

После установки закрываем окно добавления пакетов в проект и видим, что в окружение проекта добавился пакет matplotlib с его зависимостями. В том, числе был установлен пакет с библиотекой numpy. Выходим из настроек.

Теперь мы можем создать файл с кодом в проекте, например, first.py. Код программы имеет следующий вид:

Для запуска программы, необходимо создать профиль с конфигурацией. Для этого в верхнем правом углу нажимаем на кнопку Add Configuration. . Откроется окно Run/Debug Configurations, где нажимаем на кнопку с плюсом (Add New Configuration) в правом верхнем углу и выбираем Python.

Далее указываем в поле Name имя конфигурации и в поле Script path расположение Python файла с кодом программы. Остальные параметры не трогаем. В завершение нажимаем на Apply, затем на OK.

Создание конфигурации для Python программы

Теперь можно выполнить программу и в директории с программой появится файл gauss.jpg :

Графики нормального распределение гаусса

Второй пример: использование предварительно созданного виртуального окружения

Данный пример можно использовать во время изучения работы с библиотекой. Например, изучаем PySide2 и нам придется создать множество проектов. Создание для каждого проекта отдельного окружения довольно накладно. Это нужно каждый раз скачивать пакеты, также свободное место на локальных дисках ограничено.

Более практично заранее подготовить окружение с установленными нужными библиотеками. И во время создания проектов использовать это окружение.

В этом примере мы создадим виртуальное окружения PySide2, куда установим данную библиотеку. Затем создадим программу, использующую библиотеку PySide2 из предварительно созданного виртуального окружения. Программа будет показывать метку, отображающую версию установленной библиотеки PySide2.

Начнем с экран приветствия PyCharm. Для этого нужно выйти из текущего проекта. На экране приветствия в нижнем правом углу через Configure → Settings переходим в настройки. Затем переходим в раздел Project Interpreter. В верхнем правом углу есть кнопка с шестерёнкой, нажимаем на неё и выбираем Add. , создавая новое окружение. И указываем расположение для нового окружения. Имя конечной директории будет также именем самого окружения, в данном примере — pyside2 . В Windows можно поменять в пути папку venv на Envs , чтобы команда workon находила создаваемые в PyCharm окружения. Нажимаем на ОК.

Создание окружения для PySide2

Далее в созданном окружении устанавливаем пакет с библиотекой PySide2, также как мы устанавливали matplotlib. И выходим из настроек.

Теперь мы можем создавать новый проект использующий библиотеку PySide2. В окне приветствия выбираем Create New Project.

В мастере создания проекта, указываем имя расположения проекта в поле Location. Разворачиваем параметры окружения, щелкая по Project Interpreter, где выбираем Existing interpreter и указываем нужное нам окружение pyside2 .

Создание нового проекта использующего библиотеку PySide2

Для проверки работы библиотеки создаем файл second.py со следующий кодом:

Далее создаем конфигурацию запуска программы, также как создавали для первого примера. После чего можно выполнить программу.

Заключение

У меня нет богатого опыта программирования на Python. И я не знаком с другими IDE для Python. Поэтому, возможно, данные IDE также умеют работать с Pip и Virtualenv. Использовать Pip и Virtualenv можно в командой строке или в терминале. Установка библиотеки через Pip может завершиться ошибкой. Есть способы установки библиотек без Pip. Также создавать виртуальные окружения можно не только с помощью Virtualenv.

В общем, я лишь поделился небольшой частью опыта из данной области. Но, если не вдаваться в глубокие дебри, то этого вполне достаточно знать, чтобы писать простые программы на Python с использованием сторонних библиотек.

Я запускаю небольшую программу на Python, которая запускает небольшое окно, которое должно оставаться поверх всех других окон. Я считаю, что это зависит от ОС, как это делается в GNU-Linux с GNOME?

[ Обновление - решение для Windows ]

Прекрасно, я думаю, у меня все получилось. Я использую Python 2.5.4 с Pygame 1.9.1 в Eclipse на Vista, 64-разрядная версия. Таким образом, это для систем Windows. Функция SetWindowPos задокументирована здесь . Я буду ссылаться на это в моем объяснении.

Затем я установил переменную, которая вызывает «SetWindowPos» в user32:

Теперь, скажем, я только что сделал окно:

Следующая строка - это ключ. Это устанавливает окно поверх других окон.

По сути, вы предоставляете hWnd (дескриптор окна) с идентификатором окна, возвращаемым после вызова display.get_wm_info() . Теперь функция может редактировать только что инициализированное вами окно.

-1 - это наш hWndInsertAfter .

На сайте MSDN написано:

Окно можно сделать самым верхним окном, либо установив для параметра hWndInsertAfter значение HWND_TOPMOST и убедившись, что флаг SWP_NOZORDER не установлен, либо установив положение окна в порядке Z, чтобы оно было выше любых существующих верхних окон. Когда не верхнее окно становится верхним, его собственные окна также становятся верхними. Однако его владельцы не изменились.

Итак, -1 гарантирует, что окно находится выше любых других существующих верхних окон, но это может работать не во всех случаях. Может быть, -2 бьет -1? В настоящее время это работает для меня. :)

x и y определяют новые координаты для устанавливаемого окна. Я хотел, чтобы окно оставалось в своей текущей позиции, когда к нему была вызвана функция SetWindowPos . Увы, я не смог найти способ легко передать текущую позицию окна (x, y) в функцию. Я смог найти обходной путь, но предположил, что не должен вводить новую тему в этот вопрос.

0, 0, должен указывать новую ширину и высоту окна в пикселях. Ну, эта функциональность уже есть в вашей функции pygame.display.set_mode() , поэтому я оставил их равными 0. 0x0001 игнорирует эти параметры.

0x0001 соответствует SWP_NOSIZE и является моим единственным uFlag. Список всех доступных uFlags находится на предоставленной странице документации. Вот некоторые из их представлений Hex:

  • SWP_NOSIZE = 0x0001
  • SWP_NOMOVE = 0x0002
  • SWP_NOZORDER = 0x0004
  • SWP_NOREDRAW = 0x0008
  • SWP_NOACTIVATE = 0x0010
  • SWP_FRAMECHANGED = 0x0020
  • SWP_SHOWWINDOW = 0x0040
  • SWP_HIDEWINDOW = 0x0080
  • SWP_NOCOPYBITS = 0x0100
  • SWP_NOOWNERZORDER = 0x0200
  • SWP_NOSENDCHANGING = 0x0400

Так и должно быть! Надеюсь, это работает для вас!


Unix

PyCharm — это мощный IDE и возможно лучший, для языка Python. А использование горячих клавиш сильно ускоряет и упрощает разработку.
Без лишних слов представляем небольшую подборку:

Работа с закладками:

Поставить или снять закладкуF11
Аналогично с присвоением буквы или цифрыCtrl + F11
Переход к закладке (удаление — клавишей Delete)Shift + F11
Быстрый переход к закладке с присвоенным числомCtrl + Число

Редактирование:

Отменить последнее действие Ctrl + Z
Отменить последнюю отмену действия Ctrl + Shift + Z
Расширенная вставка из буфера обмена (с историей) Ctrl + Shift + V
Инкрементальное выделение выражения Ctrl (+ Shift) + W
Перемещение между словами Ctrl + влево/вправо
Прокрутка кода без изменения позиции курсора Ctrl + вверх/вниз
Переход в начало/конец файла Ctrl + Home/End
Удаление строки, отличие в том, где потом окажется курсор Shift + Del (Ctrl + Y)
Удалить от текущей позиции до конца слова Ctrl + Del
Удалить от текущей позиции до начала слова Ctrl + Backspace
Дублировать текущую строку Ctrl + D
Увеличить / уменьшить текущий отступTab / Shift + Tab
Выравнивание отступов в кодеCtrl + Alt + I
Приведение кода в соответствие Code-StyleCtrl + Alt + L
Закомментировать/раскомментировать текущую строкуCtrl + /
Закомментировать/раскомментировать выделенный кодCtrl + Shift + /
Фолдинг, свернуть/развернутьCtrl + -/+
Фолдинг, свернуть/развернуть всеCtrl + Shift + -/+
Сделать текущий скоуп сворачиваемым и свернуть егоCtrl + Shift + .
Сделать текущий скоуп несворачиваемымCtrl + .
Замена в текстеCtrl + R
Замена во всех файлахCtrl + Shift + R

Работа с окнами, вкладками:

Перемещение между вкладкамиAlt + влево/вправо
Закрыть вкладкуCtrl + F4
Открытие/закрытие окон Project, Structure, Changes и тдAltl + число
Переключение между вкладками и окнамиCtrl + Tab
Закрыть активное окноShift + Esс
Открыть последнее закрытое окноF12
Zoom, если он был вами настроенCtrl + колесико мыши

Работа с поиском:

Быстрый поиск по всему проектуДважды Shift
Быстрый поиск по настройкам, действиям и тдCtr + Shift + A
Перейти к следующему/предыдущему методуAlt + вниз/вверх
Перемещение к началу и концу текущего скоупаCtrl + [ и Ctrl + ]
Поиск в файлеCtrl + F
Поиск по всем файлам (переход — F4)Ctr + Shift + F
Искать слово под курсоромCtrl + F3
Искать вперед/назадF3 / Shift + F3
Переход к строке или строке:номеру_символаCtrl + G
Список методов с переходом к их объявлениюCtrl + F12
Список недавно открытых файлов с переходом к нимCtrl + E
Список недавно измененных файлов с переходом к нимCtrl + Shift + E
Иерархия наследования текущего класса и переход по нейCtrl + H
Иерархия вызовов выбранного методаCtrl + Alt + H
Поиска класса по имени и переход к немуCtrl + N
Поиск файла по имени и переход к немуCtrl + Shift + N
Перейти к объявлению переменной, класса, методаCtrl + B
Перейти к реализацииCtrl + Alt + B
Определить тип и перейти к его реализацииCtrl + Shift + B
Перемещение назад по стеку поискаShift + Alt + влево
Перемещение вперед по стеку поискаShift + Alt + вправо
Переход к следующей / предыдущей ошибкеF2 / Shift + F2
Найти все места, где используется метод / переменнаяShift + Alt + 7
Как предыдущий пункт, только во всплывающем окнеCtrl + Alt + 7

Генерация кода и рефакторинг:

Полный автокомплитCtrl + Space
Автокомплит с фильтрацией по подходящему типуCtrl + Shift + Space
Простой автокомплит по словам, встречающимся в проектеAlt + /
Реализовать интерфейсCtrl + I
Переопределить метод родительского классаCtrl + O
Генерация шаблонного кода (обход по итератору и тд)Ctrl + J
Обернуть выделенный код в один из шаблоновCtrl + Alt + J
Генератор кода — сеттеров, зависимостей в pom.xml и тдAlt + Insert
Переименование переменной, класса и тд во всем кодеShift + F6
Изменение сигнатуры метода во всем кодеCtrl + F6
Перемещение метода, класса или пакетаF6
Создать копию класса, файла или каталогаF5
Создать копию класса в том же пакетеShift + F5
Безопасное удаление класса, метода или атрибутаAlt + Delete
Выделение методаCtrl + Alt + M
Выделение переменнойCtrl + Alt + V
Выделение атрибутаCtrl + Alt + F
Выделение константы (public final static)Ctrl + Alt + C
Выделение аргумента методаCtrl + Alt + P
Инлайнинг метода, переменной, аргумента или константыCtrl + Alt + N
Оптимизация импортовCtrl + Alt + O

Тут представлены не все горячие клавиши, если этого для вашей работы не достаточно можете поискать нужные тут.

PyCharm has keyboard shortcuts for most of its commands related to editing, navigation, refactoring, debugging, and other tasks. Memorizing these hotkeys can help you stay more productive by keeping your hands on the keyboard. All default shortcuts are configurable and you can also assign shortcuts to any action that does not have them by default.

If your keyboard does not have an English layout, PyCharm may not detect all the shortcuts correctly.

The following table lists some of the most useful shortcuts to learn:

Quickly find any file, action, class, symbol, tool window, or setting in PyCharm, in your project, and in the current Git repository.

Find a command and execute it, open a tool window, or search for a setting.

Quick-fixes for highlighted errors and warnings, intention actions for improving and optimizing your code.

Jump to the next or previous highlighted error.

Select a recently opened file from the list.

Increase or decrease the scope of selection according to specific code constructs.

Comment out a line or block of code.

Show all places where a code element is used across your project.

Choose the right keymap

To view the keymap configuration, open the Settings/Preferences dialog Ctrl+Alt+S and select Keymap .

Enable function keys and check for possible conflicts with global OS shortcuts.

Use a predefined keymap

PyCharm automatically suggests a predefined keymap based on your environment. Make sure that it matches the OS you are using or select the one that matches shortcuts from another IDE or editor you are used to (for example, Emacs).

When consulting this page and other pages in PyCharm documentation, you can see keyboard shortcuts for the keymap that you use in the IDE — choose it using the selector at the top of a page.

Install a keymap from a plugin

Besides the default set of keymaps, you can install keymaps from plugins (such as, keymaps for GNOME and KDE): open the Settings/Preferences dialog Ctrl+Alt+S , select Plugins , switch to the Marketplace tab and search for keymap .

Tune your keymap

You can modify a copy of any predefined keymap to assign your own shortcuts for commands that you use frequently.

Import custom keymap

If you have a customized keymap that you are used to, you can transfer it to your installation.

If your keymap stopped working after an update, it is likely that the keymap is not available by default in the new version of PyCharm. Find this keymap as a plugin and install it on the Plugins page as described inInstall plugins.

Print your keymap

If you prefer a hard copy, download the default PyCharm keymap reference and print it out as a card:

Learn shortcuts as you work

PyCharm provides several possibilities to learn shortcuts:

PyCharm includes a built-in IDE Features Trainer. It provides interactive training courses to help you learn how to do some common tasks, such as refactoring code, navigating through projects, debugging, and working with version control.

Make sure the IDE Features Trainer plugin is enabled in the Installed tab of the Plugins page in the IDE settings.

To open the Learn tool window and start your exercises, select View | Tool Windows | Learn or Help | Learn IDE Features from the main menu. The tool window lists the available tutorials.

Find Action lets you search for commands and settings across all menus and tools.

Press Ctrl+Shift+A and start typing to get a list of suggested actions. Then select the necessary action and press Enter to execute it.

Find Action

To add or change the shortcut for any action, press Alt+Enter when it is selected in the list.

Key Promoter X is a plugin that shows a popup notification with the corresponding keyboard shortcut whenever a command is executed using the mouse. It also suggests creating a shortcut for commands that are executed frequently.

If you are using one of the predefined keymaps, you can print the default keymap reference card and keep it on your desk to consult it if necessary. This cheat sheet is also available uner Help | Keyboard Shortcuts PDF .

To print a non-default or customized keymap, use the Keymap exporter plugin.

Use advanced features

You can further improve your productivity with the following useful features:

If there is a group of actions that you often use, create a quick list to access them using a custom shortcut. For example, you can try using the following predefined quick lists:

Refactor this Ctrl+Alt+Shift+T

VCS Operations Alt+`

PyCharm provides a lot of typing assistance features , such as automatically adding paired tags and quotes, and detecting CamelHump words.

When the focus is on a tool window with a tree, list, or table, start typing to see matching items.

Some actions in PyCharm provide more results when you execute them multiple times. For example, when you invoke basic code completion with Ctrl+Space on a part of a field, parameter, or variable declaration, it suggests names depending on the item type within the current scope. If you invoke it again, it will include classes available through module dependencies. When invoked for the third time in a row, the list of suggestions will include the whole project.

Resize tool windows

You can adjust the size of tool windows without a mouse:

To resize a vertical tool window, press Ctrl+Alt+Shift+Left and Ctrl+Alt+Shift+Right

To resize a horizontal tool window, press Ctrl+Alt+Shift+Up and Ctrl+Alt+Shift+Down

Читайте также: