Current location - Quotes Website - Signature design - How to start using PyCharm and have an efficient Python IDE
How to start using PyCharm and have an efficient Python IDE

Initial use

When you start PyCharm for the first time, he will ask you which keyboard layout and theme you want to use. I don't like its Emacs keymap, so I used the default Mac OS X keymap and customized the shortcuts I wanted:

If this is your first time using PyCharm, and There is no configuration to import. You may want to click "Configure" in the welcome screen and set up some basic configuration:

I like to show line numbers and method separators (Editor→Appearance→Show method separators, Show line numbers):

Also, I like the Solarized theme. I installed it following the instructions and selected it as the editor's default theme → Colors and Fonts. The light version of Solarized IntelliJ had some weird color choices (for example, it used gray for default text instead of the crisper black), so I changed that on Editor → Colors & Fonts → General. My advice is don't be afraid to modify the colors to your liking. You can export your configuration in case you need to reinstall PyCharm.

Compared with some other IDEs, I think PyCharm is very clean visually. If you want a simpler user interface, you can hide the toolbar, tool buttons, navigation bar and Status Bar (on the View menu):

Virtualenv and Python Interpreter

You can create a new project with File→New Project or open an existing project withFile→Open Directory. PyCharm supports many types of Python projects, such as Django, Flask, and more. Here I will create a simple project to test the pyquery library (I will select "Empty project").

You need to tell PyCharm which Python interpreter you want to use, as it can use different interpreters for different projects. It will use this information to index all available libraries. A good practice is to create a virtualenv for each project. You can use an existing virtualenv or create a new one from PyCharm (Settings → Project Interpreter → Python Interpreters).

For this project, I will create a new virtualenv and make it available for all projects:

You can quickly search, read the instructions, and install the package from PyCharm. There's nothing you can't do in the terminal, but it makes it easier to search for packages without leaving the IDE.

Some packages may take a while to install, especially if they need to be compiled. PyCharm runs the installation process in the background, and you can see what's happening by clicking on the status bar:

As we can see, it not only installs pyquery, but also relies on packages such as lxml Installed together (as we expected):

Shortcut keys

PyCharm is Vim-less, but you can also do a lot of things with just the keyboard. You can set shortcuts to dozens (if not hundreds) of shortcut actions in Settings→Keymap.

I modified the default keymap quite a bit because I like to have shortcuts like Control-a, Control-e, Control-k, and Control-y, which are used by default for text boxes. , and there is no keyboard mapping set by default in "Mac OS X". You can also define mouse shortcuts. For example, I use Option-Click to change a quick document. If you are a Vim user, you may want to try IdeaVim, a Vim emulator plug-in. I've heard good things about this but I haven't had a chance to try it.

I use the Dvorak keyboard layout, but the annoying thing is that there will be bugs if I use the wrong shortcut keys. Someone reported this problem, French Canadian and German layouts also have this problem. This means I have to rebind quite a few shortcuts to avoid this problem.

PyCharm uses function keys, such as F1 and F2 and many more. As you probably know, on a Mac, the top keys mostly serve as the default "multimedia" keys and are activated by pressing the Fn key. We can swap this way in System Preferences→Keyboard.

I'd like to be able to control volume and change brightness without having to use the Fn key, but I also like using the function keys without having to touch the far Fn key (I'm lazy, what can I say? ). I use Palua to switch between "Multimedia" and function keys. You can use global keys to switch, or you can configure Palua to automatically switch when using specific applications. I use multimedia keys for all apps (the default) and configure Palua to use function keys for Xcode and PyCharm.

External Editor

PyCharm can launch any external tool, so I configured it to use Emacs to open the current file. This is useful when you want to do some quick editing with your favorite editor (Emacs, Vim, TextMate, etc.).

Go to Settings→External Tools, make sure "Open console" is not selected, insert the path to the program, parameters (in this case, we can use FilePath to get the full file name) and the working directory (ProjectFileDir /FileRelativeDir/).

You can assign it to a shortcut:

It is now available from the menu bar.

Running Code and REPL

PyCharm has many ways for us to run code. We can use the good old print function (or declare statement, depending on your Python version), import the code in the REPL, send the code to the console, use the debugger, or use IPython on the terminal.

Print Output

Using printing to display values ??is a useful and widely used technique, but it can lead to confusing code if used carelessly.

If the file has been selected to run, we can start by clicking the "play" button or Control-R.

If no file is selected to run, a file will be selected from the context menu and run with Control-Option-R or right-click. PyCharm will remember your selection and you can continue to use Control-R next time. This sounds complicated, but it's actually very simple. Check the manual for more information.

Console and REPL

My favorite method is to run the code in the REPL.

You can open a Python console in PyCharm's toolbar, Tools → Run Python Console (I've assigned it to Control-C). It will use IPython if available (I recommend you install IPython inside a virtualenv) and add the current file's path to Python's path. On the console, you can import the function you want to execute as usual.

Completion functionality is still available in the console:

We can use imported functions as usual, and can easily toggle console visibility using ?–4.

Execute selected code in the console

What if the code I wanted to run was a few more single lines and no formal unit tests were written (for example, maybe I was playing data) I can save it in a temporary file. We can select the code we want to run (usually I just select the entire file with ?-A) and choose "Execute Selection in Console" from the context menu (or, better yet, use the keyboard shortcut). [I have omitted some screenshots of menu items to make the article shorter.

In the following example, the title variable is available in the console because we select the entire temporary file in the console to execute:

Macros

If we could It would be nice to send the entire file to the console in one operation. Fortunately, we can record a macro. Select Select Edit→Macros→Start Macro Recording and perform the operations as before (select the entire file, send to console, switch to console). As you can see, my macro only has four actions (I pressed the down arrow key to deselect):

When your recorded macro is already in the macro menu, you can assign a shortcut to it ( I use Control-C Control-E but for some reason PyCharm only shows half of the two shortcuts).

Debugging

Many people like to use a debugger to examine data. Even though I like using the REPL, sometimes it's more efficient to debug a program, especially when inspecting complex objects. PyCharm does not allow you to set a breakpoint on an empty line, so in this short example I had to add an extra line (I used the print function, but I could have used pass) because I wanted the debugging to stop After setting the headlines variable. In real code, this is rarely necessary.

IPyhton

Finally, there is nothing wrong with using IPython to run external terminals and use features such as %run and auto-reloading.

Searching for commands

It's easy to become overwhelmed because there are so many commands. If you're using PyCharm on a Mac, you can use Help→Search as usual, or you can use the Help→Find Action on any platform. It lets you search for any PyCharm command, including those not available from the menu. (Emacs users will note that this is somewhat similar to Emacs' M-X). This is a very useful and powerful feature and I use it all the time.

Code completion

The code completion feature on PyCharm is first-rate. By default PyCharm will give suggestions as you type:

Since this feature can be somewhat power-hungry, you can disable it by selecting File→Power Save Mode. You can still use this feature explicitly via Control-Space.

As you type, you can narrow the list of suggestions by typing a substring:

Alternatively, you can type the first letter of CammelCaseClasses or function_names_with_underscores:

If you type Control-Space once, PyCharm will try to list the most relevant items:

If you type Control-Space again, every name it knows will be listed. This may be overwhelming, but be aware that it lists the function name_of_mother in the file bar.py that does not import it.

But often you just want to complete the name of a local variable in an open buffer. This functionality was available in Emacs and Vim a long time ago, and now it is also available in PyCharm. The manual calls it Hippie Completion, but the actual command name (i.e., the one you'll find in the Find Action) is "Cyclic Expand Word", and in my testing, it even worked for docstrings.

Code completion may not work in some cases, such as when a library does not have type hints. This StackOverflow page suggests setting breakpoints in the PDB and listing all possible properties with dir. A similar solution is to create a breakpoint in PyCharm and execute an expression - by clicking on the last icon in the debug toolbar (or using the appropriate keyboard shortcut). In this case, the expression I evaluate is "dir(r)".

Accessing documents

PyCharm has three ways to access documents: quick definition, quick document, external document, and parameter information. You can access them from the View menu or from their respective shortcuts.

Quick Definition will display the entire definition of the symbol (class, method, function, etc.) (duh!), including the documentation of course. If you just want a quick look at a definition, jumping to it is useful.

Quick Documentation will display the symbol's documentation and signature.

Finally, external documentation, and parameter information is very simple. The first opens the document in the default browser, and the second gives parameter information for a function or method (useful for quickly looking up the names of keyword arguments, for example).

External documentation works for Python (of course), PyQt4, PySide, GTK, WX, numpy, SciPy, and kivy, and you can add a path to the external documentation in Settings → Python External Documentation .

Code Quality

As you type, PyCharm will check whether your code complies with PEP8. It will let you know if you have too many spaces or empty lines etc. If you wish, you can configure PyCharm to run pylint as an external tool.

Find your way through the source code

PyCharm starts to become powerful when you master its navigation commands. It can jump to classes, functions, etc. On Mac you can use ?-B or ?-Click to jump to the definition of a class, method, function, variable, or on Windows and Linux use Ctrl-B or Ctrl-Click.

The mechanism for navigating to a class, file or symbol is almost the same. When you enter a string, you will see a dialog box that includes results from projects other than your current project and the same city match filter. Go to the navigation menu or use the corresponding keyboard shortcut:

This is a typical dialog box for a class definition:

You can enter part of the name, including the file extension.

For example, if you want to open a JavaScript file in a Django project but can't remember its name, you can search for ".js".

These features allow us to browse source code very quickly. Suppose we are studying the source code of Django, and what we want to see is the process of feature implementation. We don't know its definition, so we go to Navigate → Symbo (?-?-O), type "render", and select the first option (we can see it's defined in django.shortcuts). If we hide the navigation bar, we can use Navigate→Jump to the navigation bar (?-↑), quickly display it and see the file location (django→django→shortcuts.py):

Sometimes after removing Code completion will be more efficient after the parts that you are not interested in. In the example below, I removed the relevant JavaScript as a result, resulting in a much cleaner list:

PyCharm lets you collapse blocks like classes, methods, and functions, but you can create your own Folded area. This is useful when it comes to groups of things (classes, methods, functions, etc.). These modules, if collapsible, would allow us to focus on specific areas of the code. You can display all regions in the list file via Navigate→Custom Region or using the corresponding keyboard shortcut. Unfortunately there is no way to list all areas in one project.

Unit Tests

Before we can run the test files, we need to add a new run/debug configuration. We go to Run→Edit Configurations and click on the plus button in the upper left corner. Then, we select "Python tests" to start testing. In this example I will use unit tests:

Finally, we need to add the folder for these tests and select the correct Python interpreter:

Now just like when we run the code Likewise, we can run our tests: by clicking on the toolbar or selecting Run→Run (Control-?-R). This will open a dialog box where you can select the code you want to run (you can run others). You can do all tests or just the cursor.

When you run the test, PyCharm will remember your last selection so you can repeat the test using Control-R. This is useful if you solve a specific test situation and want to run it multiple times, but not other tests. You don't need to locate the test file you want to run; you can run tests from any file. You can test your code by selecting Navigate→Test (or the corresponding hotkey).

Handling multiple files

As you can see, PyCharm uses a tag for each file

To switch to tags, we can use the command select Next tab or select previous tab. The default shortcuts are Control-→ and Control-←, but OS X uses these keys, letting me rebind them to Control-?-N

and Control-?-P (in Terminal I use the same shortcut to switch tabs).

A more direct way to select tags is to use Navigate→File, or View→Recent Files (?-E) and View→Recently Changed Files (?-?-E). The last two commands will display files and you can narrow the selection by entering substrings.

In the example below, I only need to enter the "?-E", "S", "ENTER" keys to enter the tag of the scratch.py ??file:

Multiple windows

PyCharm supports Multi-window, although not as good as Emacs, is enough.

There is no assigned shortcut to handle split windows by default, so you have to do it yourself. These are the shortcuts I use:

Split vertically, Control-S

Split horizontally, Control-H

Unsplit, Control-C Control- U

Unsplit all, Control-C Control-A

Go to the next splitter, Control-C Control-N

Go to the previous splitter Page separator, Control -C Control -P

Move to relative group, Control -C Control -M

It is more convenient to drag labels when there are two panes.