PyCharm complete guide

1. PyCharm  debugging and operation

1. Four ways to run Python

1. Set up the Python interpreter

PyCharm only provides an integrated development environment, and you still have to rely on the Python interpreter when executing Python programs.

There can be multiple versions of Python interpreters on a computer, so before you execute a Python program, you must first tell PyCharm which Python interpreter you want to use to execute the program.

Open the settings, search for Interpreter (as shown below), and you can add your Python interpreter.

After the setting is complete, you can see such a piece of content on the main interface. If you want to read the code of some built-in modules in the future, you can click here directly. 

2. Run the Python program

Once the interpreter is set up, you can run Python programs directly.

There are three methods:

The first

Right click - click Run to run the program.

From the right button, you can see that there is a shortcut key for Run, you just need to use ctrl+shift+F10 to run the program.

the second

After you run the script once, PyCharm will automatically record a running record for you.

So you can directly click here in the future to start the program directly. 

third

If you have the following code in your program:

if __name__ == '__main__':
     main()

 The following run buttons will appear, click the first one is Run.

3. Run related shortcut keys

Shift + F10: Run the file in the current running configuration, which is equivalent to Ctrl + Shift + F10;

Shift + F9: Debug files in the current run configuration;

Alt + Shift + F10: A pop-up menu allows you to choose which file to run (you have to set the running configuration in advance);

Alt + Shift + F9: A pop-up menu allows you to choose which file to debug (you have to set the running configuration in advance);

Ctrl + Shift + F10: run the main function;

2. Execute the program by specifying parameters

How do you usually execute your project when you run it in Pycharm? My approach is to right click, then click Run, or use
the shortcut key Shift + F10.

Sometimes, when running/debugging a script, we need to specify some parameters, which can be specified directly on the command line.

Suppose on the command line, the command to run the script looks like this:

python main.py init --local

For students who have just used Pycharm, they may not know that Pycharm can also specify parameters. Click on the location in the picture below:

Enter the setting panel and fill in the parameters in Script parameters. 

At the same time, at the bottom of the above picture, you can see that it is very convenient to switch the interpreter here, which is much easier than running here.

3. Super detailed graphics and texts teach you to debug code

1. The process of debugging

Debugging can be said to be a must-have skill for every developer, and it is very useful in daily development and troubleshooting.

The debugging process is divided into three steps:

  1. Step 1: Put a breakpoint where you want to debug
  2. Step 2: Run the python program in debug mode
  3. Step 3: Use various means to start code debugging

First of all, the first step and the second step, I use the following picture to represent: 

Click the little spider in the picture above, and after the debug mode is turned on, a tab will pop up under PyCharm.

There are many buttons in this tab, including:

  1. variable viewing window
  2. debug control window
  3. thread control window
  4. program control window

In the variable viewing window, you can view the current program progressing to the breakpoint, all ordinary variables and special variables, each time you execute a line of code, these variables may change accordingly.

If your program is multi-threaded, you can switch threads through the drop-down box in the thread control window.

The above two windows are relatively simple, I have briefly mentioned them, and the following will mainly focus on the debugging control button and program control button.
In the debug control window, there are 8 buttons in total. What are their functions?

  1. Show Execution Point: No matter where the cursor is in your code editing window, as long as you click this button, it will automatically jump to the place where the program is running.
  2. Step Over: During single-step execution, when a sub-function is encountered in a function, it will not enter the sub-function for single-step execution, but will stop after the entire sub-function is executed, that is, the entire sub-function is regarded as one step. In the absence of sub-functions, it has the same effect as step into. Simply put, the program code passes over the sub-function, but the sub-function will be executed without entering.
  3. Step Into: During single-step execution, it will enter and continue single-step execution when it encounters a sub-function, and some will jump to the source code to execute.
  4. Step Into My Code: During single-step execution, enter and continue single-step execution when encountering a sub-function, and will not enter the source code.
  5. Step Out: If you enter a function body, you read two lines of code and don’t want to read it, jump out of the current function body and return to the place where this function was called, that is, use this function.
  6. Run To Cursor: Run to the cursor, saving you from having to hit a breakpoint every time.
  7. Evaluate Expression: Calculate the expression, in which you can execute some code yourself.

The above seven functions are the most commonly used functions. The general operation steps are: set a breakpoint, run debug, and then F8 for single-step debugging. When you encounter a function you want to enter, press F7 to enter it. When you want to come up with shift + F8, skip it if you don’t want to see it. place, directly set the next breakpoint, and then press F9 to pass.

Just look at this picture (the 6th point below is wrong, it should run to the cursor, not the next breakpoint):

In the program control window, there are 6 buttons. What are their functions? Just look at the picture below.

2. Debug related shortcut keys

  • Shift + F10: Run the file in the current running configuration, which is equivalent to Ctrl + Shift + F10;
  • Shift + F9: Debug files in the current run configuration;
  • Ctrl + Shift + F10: run the main function;
  • Alt + Shift + F10: A pop-up menu allows you to choose which file to run (you have to set the running configuration in advance);
  • Alt + Shift + F9: A pop-up menu allows you to choose which file to debug (you have to set the running configuration in advance);
  • F8: single-step execution, do not enter the function;
  • F7: single-step execution, enter the function;
  • Alt + Shift +F7: single-step execution, only enter the function written by yourself;
  • Shift + F8: Jump out of the function body;
  • Alt + F9: Run to the line where the cursor is located;
  • F9: Run to the next breakpoint;
  • Ctrl + F2: terminate the debugger;
  • Ctrl + F5: run again in debug mode;
  • Ctrl + Shift + F8: View all set breakpoints;
  • Ctrl + F8: Toggle breakpoint (if there is a breakpoint, cancel the breakpoint, if there is no breakpoint, add a breakpoint);
  • Alt + F8 calculation expression (you can change the variable value to make it effective);

4. After the program is over, it can still be debugged

If we are in a crawler project, we will use regular expressions to match the content we want to grab. Regularly, how many people can do this kind of thing in one step, and it usually takes many times of debugging to match as expected. After we changed the regex once and ran it, we needed to grab the request from the website again to find that there was no match, and then changed the version, and we also needed to initiate a request to run it again, but we still found that there was still no match, and often repeated Students with poor regularity may have to make dozens of attempts.

(The above example may not be appropriate. After all, there are many ways to realize that there is no need to resend the request. It just lists a very clumsy and inefficient debugging process. Just take a look.)

And in our dozens of debuggings, it is meaningless repetitive work to initiate requests to the same website. If in Pycharm, like IPython Shell and Jupyter Notebook, you can remember all the variable information after running, you can adjust our code by executing command expressions without re-running projects or scripts. Regular debugging.

The answer is of course yes.

Suppose I am debugging the following simple lines of code. A breakpoint is set on line 3. Then click the Show Python Prompt button shown in the illustration.

Enter the interface of the Python Shell. This Shell environment is connected with the program environment we are currently running. Variables can access each other. Now you can easily debug. 

We made a breakpoint above for the convenience of illustrating this effect. Not that it has to be interrupted. If there is no break point, all variables can still be viewed and manipulated on this interface after the script is executed. 

Now we can meet our debugging needs, but every time we run the script, we have to manually click Show Python Prompt, which is a bit troublesome. Um? In fact, there is a place where you can set it to be turned on by default. This switch is still relatively secret, and most people really can't find it.

You need to click on the icon location Edit Configurations. 

Then tick here to select:

After setting it, every time you run the postscript, it will store the values ​​of all variables for you by default and open the console command line debugging interface for you.

In addition to the above method, there is actually another method to execute command expressions during debugging, and this kind of method may be familiar to everyone, so I will mention it here as a summary. But in terms of function, it is not as convenient and easy to use as the above method. Because of this approach, you must be required to run the project in debug mode with breakpoints.

The way to use it is, after you hit the breakpoint, right-click at the position shown in the icon to use Evaluate Expression:

An Evaluate Expression window pops up, where you can run command expressions and directly manipulate variables.

5, 7 steps to achieve remote code debugging

Under normal circumstances, our development and debugging are all done on a personal PC. If you encounter a problem, open the Pycharm debugger and you can quickly find the problem.

But sometimes, the operation of the project code depends on the operating environment, and it must be run on the server where the relevant dependent components are deployed, which directly causes us to not be able to debug locally.

For this particular scenario, as far as I know, there are two solutions:

  • pdb;
  • remote debugging;

As for remote debugging, we can use the graphical interface of PyCharm to debug the code on the remote server on our PC. It is not much different from local debugging. How to debug is still how to debug now.

The difference is that local debugging does not require prior configuration. As long as your code is ready, you can start debugging at any time, while remote debugging requires many pre-steps. Here I will teach you how to configure the remote debugging environment.

1. Create a new project

First of all, we need to create a new empty project in Pycharm, and then we will place the project code on the server in this project directory. My name here is NOVA, you can define it yourself.

2. Configure Connection Server

Tools -> Deployment -> configuration

Add a server:

  • Name: Fill in the IP of your server;
  • Type: set to SFTP;

After clicking OK, enter the following interface, you can fill in the information according to my remarks:

  • SFTP host: public network ip;
  • Port: The ssh port opened by the server;
  • Root path: the project code directory you want to debug;
  • Username: the user you use to log in to the server;
  • Auth type: login type, if you log in with a password, it is Password;
  • Password: After selecting a password to log in, enter your login password here, and you can choose to save the password;

Please note here that you must ensure that your computer can ssh to your server, whether it is key login or password login, if the whitelist restriction is enabled, you must first remove it. 

After filling in, switch to the Mappings tab, at the arrow position, fill in \: 

After the above server information configuration is filled in correctly, click OK.

Next, we need to connect to the remote server.

Tools -> Deployment -> Browse Remote Host:

3. Download project code

If the server login information filled in before is correct, you can now see the remote project code. 

Choose to download remote code locally: 

Download completion prompt:

The current IDE interface should look like this. 

4. Download the remote interpreter

Why is this step needed?

Remote debugging runs on a remote server. In addition to relying on other components, it also has many Python dependent packages that we do not have locally.

Go to File -> Settings and click the icon to add a remote interpreter.

Fill in the remote server information, the same as before, no more details. 

After clicking OK, the remote interpreter will be downloaded automatically. If your project is relatively large, this time may be longer, please wait patiently. 

5. Add program entry

Because we want to debug locally, you must know the entry program of your project. If this entry program is already included in your project code, please skip this step.

If not, please generate the entry program yourself.

For example, the project on my side runs as a service on the server. And we all know that the entry point of the service is the Service file.

cat /usr/lib/systemd/system/openstack-nova-compute.service:

[Unit]
Description=OpenStack Nova Compute Server
After=syslog.target network.target libvirtd.service

[Service]
Environment=LIBGUESTFS_ATTACH_METHOD=appliance
Type=notify
NotifyAccess=all
TimeoutStartSec=0
Restart=always
User=nova
ExecStart=/usr/bin/nova-compute

[Install]
WantedBy=multi-user.target

See that ExecStart yet? That is the entry point of our program.

We just need to copy it to our Pycharm and synchronize the file remotely. 

6.  Setting before debugging

Turn on code automatic synchronization, so that Pycharm can recognize our code modification and submit it to the remote server for us. 


Enable Gevent compatible. If it is not enabled, problems such as inability to debug, or inability to track/view variables may occur during the debugging process .

7. Start debugging code

At the entry file of your program, right-click and select Debug.

If your program entry needs to introduce parameters, this is often the case, you can configure it here.

After configuration, click Save. 

8. Friendly reminder

According to the trial debugging code in the article, the code will be automatically synchronized to the remote end. Do not use it in the production environment, but must use it in the development environment, otherwise you will be responsible for the consequences.

Debugging tools provide programmers with great convenience, but I still hope you don't rely too much on them. Try to pursue a shape every time you write code, and improve your coding ability.

6. Use Vagrant to build a one-and-done development environment

During the development process, it is inevitable to encounter the embarrassment of half an hour of development and half a day of environment.

Sometimes the environment I have worked so hard to build on my computer can only be used by myself and cannot be reused by colleagues, which causes an extreme waste of team labor.

It allows you to work hard to build a Python project operating environment on your computer, package it to your colleagues, and let them enjoy the fruits of your labor.

1.  Download and install Vagrant

Vagrant download address: Install | Vagrant | HashiCorp Developer

After the installation is complete, execute the vagrant box add hashicorp/precise64 command, and a mirror image will be downloaded on your computer. This mirror image is only for demonstration purposes. If you need it, you can use your customized mirror image of the corresponding system.

When downloading, you will be prompted to choose virtualization software. Here we choose virtualbox (note: please install virtualbox in advance), which is free and lightweight.

2. Initialize the project

Enter my newly created project directory ~/Code/Python/Vagrant-Project and execute vagrant init hashicorp/precise64 initialization.

Finally, start the virtual machine directly with this command vagrant up:

After the virtual machine starts, you can use vagrant ssh to directly ssh into the virtual machine (Windows can only use remote
login software to log in to 127.0.0.1:2222, such as Xshell, or use Tools -> Start SSH Session).

In this image, Python 2.7.3 is built in, which is enough for demonstration purposes only.

The /vagrant/ directory in the virtual machine corresponds to the project root directory on your host:

If you want to add more folder mappings, you can edit the Vagrantfile and add the following line before end:

 config.vm.synced_folder "/Users/MING/src", "/srv/website"

Then execute vagrant reload.

3. Configure PyCharm

PyCharm is indeed the most professional Python IDE, and it also provides very good support for Vagrant. But before using it, you need
to configure it.

First, make sure your vagrant plugin is installed:

Then, configure vagrant information in Tools -> Vagrant:

Finally, add the Python interpreter in the Vagrant virtual machine in Project -> Python Interpreter:

After configuration, no matter in Setting:

The Python interpreters seen in the project interface are all Python in Vagrant:

In such an environment, all the Python project files you create will be synchronized to the /vagrant/ directory in the Vagrant virtual machine. When you run a Python project locally, it is actually running in the Vagrant virtual machine.

If your Python project needs to rely on a lot of components, you can install all these components in this Vagrant
virtual machine, package them into a mirror, and then send the mirror and project (including .vagrant folder and Vagrantfile) to
you Colleagues, they will soon have a project operating environment that can run stably. 

2. PyCharm  interface and typesetting 

1. Create an interface with super high value

1. Your IDE

When you download a PyCharm from the official website, if you don't make some personalized settings, I believe you will not be able to tolerate the default ugly interface, just like the following.

In the above interface, there are many places to complain about, and I have marked them all:

  1. The English in the menu bar is too ugly, and the font is too strange. This is extremely inconsistent with the size of the title bar font.
  2. The Chinese font is too ugly. Compared with the code on the right, it is really hard to read.
  3. The background is all white, I won't say it hurts the eyes, it doesn't feel like a geek at all.
  4. The code font is too ugly, too small, and the code highlighting experience is too poor.

A beautiful IDE interface can improve the joy of writing code. Next, I will address the above questions and introduce how I created a suitable and high-value IDE interface for me. 

2. How to build

Let's solve the first, second and third problems first.

Click File - Setting to enter the following interface, and set the corresponding parameters according to the figure.

After the setting is complete, click Apply or OK to see the effect picture, is it more comfortable? 

Let's solve the fourth problem.

Click File - Setting to enter the following interface, and set the corresponding parameters according to the figure.

Once this is set, your code will have a hacker-like feel to it. 

Of course, if you are not very satisfied with this highlight color, you can also customize it. After modification, there will be a preview window below. Very convenient. 

3. Theme download

Pycharm provides us with very limited themes, only a few. But it provides customization functions, which can be praised. But not everyone has the artistic talent to spend a lot of energy to make a very good-looking theme.

Here, I will introduce you several very useful theme download sites.

  1. WordPress themes - Managed WordPress Hosting - Publish in Minutes - EasyWP
  2. Home - ThemesMap

Support the download of a full range of JetBrains themes, including: InteliJ IDEA, PhpStorm, PyCharm, RubyMine, WebStorm and AppCode.

After downloading, it is a jar package.

You need to import via File - Import Settings. 

Finally, select the imported theme in File - Setting - Editor - Colors & Fonts. 

2. Close the unsightly wavy lines

Let me give a small code example first, think about it, why name, my_name will not have wavy lines, but myname
and wangbm will have wavy lines?

Pycharm itself will check the variable name in real time. If the variable name is not an existing English word, a wavy line will appear. When there are multiple words in a variable, Python recommends using underscores to separate them (other The language may be accustomed to using camel case naming, but Python uses underscores), so in Pycharm, my_name is canonical, and myname will be treated as a word, because it does not have it in the word library, so myname is Irregular.

Everyone's variable naming habits are different. If you use a lot of variable naming methods in the style of myname in your project, like the following (just find a piece of cloudinit code), it is quite uncomfortable. There is always a The code has the illusion of bugs. 

So how to turn off this non-syntax level tilde?

It's very simple, its switch is on the button like the avatar in your lower right corner.

Then select the Syntax level. The same piece of code, the effect is as follows, much cleaner. 

3. Turn on the eye protection mode

Eyes facing electronic products are prone to dryness. For programmers, people who have been working with computers for a long time, they should pay more attention to eye protection
.

In order to protect their eyes, some white-collar workers usually set the
background color of some office software (such as word, excel, and resource manager) to an eye-protecting color, which is similar to what we call forgiveness hhh.

Is there a way to set it like this in PyCharm?

Of course there is.

I can tell you clearly with a picture, the setting method is as follows:

Setting the eye protection color will sacrifice the appearance of PyCharm, and it is no longer the cool geek style, which requires you to choose a trade-off

4. Open multi-line tab page

When PyCharm opens a file, it takes up a label surface.

Have you found that, unknowingly, there are more and more open files, so many that a line of tabs can’t fit,
PyCharm will hide the tabs that can’t fit, and tell you how many files are hidden in the form of numbers .

Click on the number 5, you can see which files are hidden.

At this time, you will definitely say, why can't PyCharm be displayed in multiple lines if it can't fit in one line?

The answer is, it's not that you can't, but you need to set it up.

As shown in the figure below, uncheck the single line display. 

After setting, which files are very clear. 

5. Turn off the annoying light bulb prompt

When we have grammatical errors in the code, or the code does not conform to the pep8 code specification, the mouse selects the problematic code, and a small light bulb will automatically pop up. This light bulb is divided into colors. If it is a red light bulb, it is generally Grammatical issues, if not dealt with will affect the code running. And if it is a yellow light bulb, it is just a reminder that the code is not standardized, etc., and it will not affect the operation of the program.

Although this light bulb is a good intention, I think it is a bit redundant (maybe I don’t have the habit of using it personally), and there will be
red squiggly lines if there are grammatical errors. You might say that the light bulb not only acts as a reminder, but also can automatically correct the code
. I personally feel that it is not as efficient and accurate as manual correction.

Based on the fact that sometimes, as this friend on Zhihu said, our code will be blocked and we will often be delayed. This is indeed an annoyance
.

I researched it, and there is a switch button in Pycharm (version 2018). Uncheck the option (Show intention bulb) in the picture below to turn off this function.

6. A must-see for small screens: turn on the coding mode for large screens

If you use a laptop to write code, then you must know that the experience of writing code on a small screen is really terrible.

For this reason, here are two tips to make it easy for you on a small screen.

first trick

Click the picture below to open the full screen mode:

If you feel that the path is a bit long every time you set it like this, you can set a shortcut key for it:

second trick

If your PyCharm has too many toolbars enabled, most of the space on the left, right, and bottom is taken up by the toolbars.

At this time, you can use the shortcut key: Ctrl + Shift + F12 to hide all these toolbars, press it again after hiding, and the original
interface will come back. 

7. Must-see on the big screen: view the code in split screen

If you need to write two codes in one file, and the two codes are far apart. Then you can use the file to open
the split screen mode.

There are two types of split screen:

  • vertical screen

  • Horizontal screen 

Then how to open it?

Right-click the tab, there will be the following two options, just click. 

8. The code is too long and automatically wraps

When using PyCharm code, some single-line codes are relatively long or the screen is relatively small, and it is often necessary to manually pull the scroll
bar to see the entire code.

If you don't want to move the scroll bar, you can actually set the code that exceeds the screen width to automatically code.

Right-click and check the Soft-Wrap option to enable automatic line wrapping:

The effect is as follows:  

3. PyCharm  code editing

1. Override the correct posture of the parent class method

When you want to override a method of the parent class in the subclass.

Usually a function is manually defined, and then the super expression is written.

If you use PyCharm in such a clumsy way, it's really buried such a good software.

The correct posture to override the parent class method in PyCharm is to use the shortcut key: Ctrl + O (note that it is the letter O, not the number 0).

The effect is as follows:

2. Indentation and anti-indentation

The shortcut key for indentation is: tab

The shortcut key for anti-indentation is: Shift + tab

3. Implement the correct posture of the interface method

When you want to implement a method of the base class in the class.

Usually, a function is defined manually, and then the specific logic is written.

If you use PyCharm in such a clumsy way, it's really buried such a good software.

The correct posture to override the parent class method in PyCharm is to use the shortcut key: Ctrl + I (note that it is the letter I, not the number 1).

The effect is as follows:

4. Quickly open a new line

When your cursor is not at the end of a line of code, and you want to change the line, you usually switch to the end of the line first, and then press Enter.

In fact, these two operations can be combined into one shortcut key to complete.

That is: Shift + ↩, no matter where your cursor is, it will start a new line, the effect is as follows:

5. Variable names can be converted to upper and lower case with one click

Constants usually exist in uppercase. If you accidentally write in lowercase, you can also use the shortcut keys Ctrl + Shift + U
to convert.

The effect is as follows:

6. Code blocks can be folded anywhere

To read the source code of a new project, you should first understand the overall logic of the code. At this time, we usually fold those that are more detailed
.

But in PyCharm, only the overall code block by default, such as a class, a function, an if code block, and a for loop code block, will have a folding button.

For this kind of fold/anti-fold button, you can use the following two sets of shortcut keys:

  • Fold: Ctrl + -
  • Unfold: Ctrl ++

But sometimes, we don't want to fold the entire code, but just want to fold a large piece of code that is temporarily useless to us
. Can that be done?

The answer is yes.

As long as you first select the code you want to fold, then press and hold Ctrl followed by .

The effect is as follows: 

In addition, there is a set of shortcut keys to say:

  • Ctrl + Shift + +: Expand all code blocks;
  • Ctrl + Shift + - : fold all code blocks;

7. Delete and cut skills

delete single line

Shortcut key: Ctrl + X

Copy current line to clipboard

Shortcut key: Ctrl + C

cut current cut and paste

Shortcut key: Ctrl + D

8. Use of historical clipboard: Paste from History

On Windows, there is a clipboard artifact - Ditto, which can save all the content you have copied and pasted so that you can reuse it.

There is an artifact on the Mac called Alfred, which also has similar functions.

If you haven't used Ditto and Alfred, it doesn't matter, in fact, PyCharm also has such a function.

Just hold down Ctrl + Shift + V to bring up the clipboard like below.

Here I prepared Hello World in several programming languages ​​in advance, the effect is as follows:

You can call up this window by right-clicking:

9. When using a function, quickly check what parameters the function has

Shortcut key: Ctrl + P

10. Auto-correction and auto-completion

Shortcut key: Ctrl + Shift + ↩, automatically end the code, automatically add a semicolon at the end of the line:

Shortcut key: Alt + ↩, also known as the universal key, shows the intended action and quick fix code: 

Shortcut key: Ctrl + Shift + J, intelligently splicing the code into one line:

Shortcut key: Ctrl + ↩, intelligently split and spliced ​​lines (not practiced). 

11. Beautify the output result: Show as JSON

When you use PyCharm to run the program, if the JSON string is printed, it is very unfriendly to the human eye.

For example, such a piece of code:

member = '{"name":"xiaoming", "gender": "male", "age": 18}'
print(member)

At this time, you can right-click in the output window and select Show as JSON, and PyCharm will open a new temporary file to display the formatted JSON string.

This feature is not available in lower versions of PyCharm.

At the same time, I found that this feature has two disadvantages:

1. It can only beautify the printed JSON string. There will be a little problem when beautifying the printed dictionary.

For example, such a piece of code:

member = {"name":"xiaoming", "gender": "male", "age": 18}
print(member)

2. There cannot be [] in the printed JSON string, otherwise there will be problems in parsing.

12. Display contextual information

If a class definition is written very long, like the following.

You are in such a position that people who are not familiar with the framework code have no idea which class they are currently in.

PyCharm provides a shortcut key: Alt + Q to display contextual information. 

If the field of view is a little lower, you don't even know which function you are in?

Press this set of shortcut keys: Windows is Alt + Q, and it will display which function you are currently in. 

13. One-key preview module documents

Ctrl + left mouse button, you can realize the function jump to view the source code, which is a common skill that almost every PyCharmer will know
.

Here are two other similar tips, quick view function documentation and preview source code.

At the beginning of the function, use three quotation marks " to contain the content, which is called the function document (DocString).

When writing code, it is a good coding habit to write the interface document of the function by the way. It introduces the parameter types and
descriptions of the function, the return value type and examples, and some simple Example Usages are also written to help understand and use.

At this point, Flask can be said to do a fairly good job.

Here is an example:

If we forget this usage when using this class, we can hold down Ctrl + Q to quickly preview the
LocalStack interface document on the current page. 

Similarly, if you are interested in the code logic of this class or function, you can also use the quick preview to display the
source code on the current page.

The shortcut key is: Ctrl + shift + i.

The effect is as follows:

If there are multiple functions with the same name detected by PyCharm, you can click here to select and view: 

These two shortcut keys are more convenient than using Ctrl + left mouse button to jump into the source code. Just like the WeChat applet, it will be burned after use, no new tab page will be created, and there is no need to jump back and forth page. 

Four, PyCharm  shortcut and efficiency

1. Complicated operations can be recorded as macros

If you are using PyCharm, some operations are more complicated (many steps), and the frequency of use is particularly high.

Then you can consider using its own macro recording tool.

It will record a series of your operations. When you want to use it, just call it directly.

Here, I take recording a macro of ڢᴻڍහ as an example: first fold the function according to the above method, then press Ctrl + Y to delete the line, and the function is deleted.

Methods as below:

After recording, you can first locate the function you want to delete, click Edit - Macro in the menu bar and select the macro we just recorded to play the macro.

It is a bit cumbersome to play the macro in this way. I personally suggest that you define a shortcut key for this macro, which will make it easier to play the macro. 

When setting shortcut keys, be careful not to conflict with existing shortcut keys.

After setting, check Macro and find that PyCharm has bound this shortcut key to this macro. 

Then you can use this shortcut key to delete a function (in fact, this is just to delete a code block, but only the setting method is discussed here). 

2. Use favorites to collect key code bits

In a project, there will be many key code logic entries, such as the OpenStack framework I use:

  • Create a virtual machine entry
  • Delete the entry of the virtual machine
  • Entry point for virtual machine migration
  • etc...

Codes that are more critical and frequently opened like this can be stored away at ordinary times. When you need to use them, you don’t need to click and open layer by layer in the project tree
, then open the file, and then find the corresponding function.

The shortcut key to add to favorites is: Alt + Shift + F, after pressing, it will let you choose which favorite to add, you can also choose to create a new favorite.

After adding to favorites, you can use the shortcut key: Ctrl + 2 to open the favorites toolbar, and click the corresponding position to jump.

If you want to modify the name of the favorites, you can right click and there is a Rename Favorites List button. 

Personally, I feel that this function is much weaker than bookmarks. Bookmarks can rename locations, but favorites cannot name favorite locations

3. A set of shortcut keys to precisely open the toolbar

In PyCharm's powerful functions, every space is not worth wasting.

Around it, we can see a bunch of buttons, click on these buttons, and the corresponding function window will appear.

If you use the mouse to click one by one, it will consume a lot of energy to find a position on the screen of Nuoda and click. Is there any way to
control it with shortcut keys?

Click View -> Tool Windows to see which windows are currently open (the unopened windows will not be displayed here
), and you can also see their shortcut keys.

After careful observation, it is not difficult to find that the serial number of the shortcut key is actually indicated at the front of the button. So even if you forget it, it doesn't matter
, just glance at the serial number with your eyes, and then press Command in front of the serial number.

If you want to set or modify their shortcut keys, you can set them in Keymap -> Tool Windows:

4. Use templates to quickly catch exceptions

How do you do it when you want to catch exceptions for a block of code?

First write a try on it, then indent the code block, and then write excep..

This method is relatively blunt and extremely inefficient.

A method is recommended here, which can use try...except... to quickly surround the code.

The effect is as follows:

  1. Select the code block first
  2. Hold Ctrl + Alt + T
  3. Choose try/except template

From the drop-down options, in addition to try/except and try/finally, there are:

  • if
  • while
  • Comments

But these, compared to using the original method, I personally feel that it is not easier, because of this function, I use more to catch
exceptions. 

5. Quickly enter custom code snippets

There is a function in PyCharm called Live Template, which can be used to customize some commonly used code snippets.

For example, the following paragraph is almost necessary for writing Python scripts

if __name__ == '__main__':

When you code python code in PyCharm, as long as you enter main, PyCharm will find the defined code snippet in the Live Template, and then just press Enter directly to generate this code.

As another example, I usually define simple decorator code:

In this way, when I want to define the simplest decorator, I just need to enter deco and then directly press Enter. 

6. Code template, efficient coding

The code template provided by Pycharm can be said to be a very practical function. It can generate a piece of content for you according to your preset template when you create a new file, such as interpreter path, encoding method, author details, etc.

In addition to initializing files when creating new files, when developing and writing code, you can also use the practical code templates that come with Pycharm to improve your coding efficiency.

When you type Ctrl + J on the keyboard, you can call up a panel, as you can see from the figure below, there are many preset templates in it.

If we want to select the last main, we can continue to type main, and then we can directly generate the following code that we usually type in manually. 

Here is another example, the for loop can be written like this.

7. Code encapsulation, one step in place

When the number of lines of code in a main function increases, the readability of the code becomes worse and worse. The usual practice is to encapsulate the code into multiple functions according to the function.

The process is nothing more than:

  1. Define a new function in place;
  2. Copy the original code into this function;
  3. And replace the original code with the function call;

If your refactoring workload is not very large, you can do these things manually.

But when you are refactoring a project code, you may need a more efficient packaging technique.

In PyCharm, various forms of shortcut methods for code refactoring are provided. The most common one is to refactor the variable name: shift+F6. What I want to introduce to you today is the refactoring of the method, that is, the quick encapsulation of the code. Skill.

Suppose, I now have the following piece of code, the code marked in the red box is placed in the main function, which is not suitable, and this code cannot be
seen at a glance what it is doing. How to encapsulate it will help us clarify the logic of the entire main program.

Select the code you want to encapsulate, and then press and hold Ctrl + Alt + M, the following interface will pop up, according to your needs, modify the function name, select parameters and return values.

When everything is ready, click OK, and PyCharm will automatically define a function name for you in the appropriate position, and put the code you selected into it, where the parameter names and return values ​​are also in accordance with your requirements, the effect is as follows:  

8. A must for reptiles, one-click quotation marks

When writing a crawler, for convenience, we often copy the headers corresponding to the request from the browser F12 to our code.

However, the headers copied from the browser are not quoted, but the headers in our Python need to pass parameters in the form of a dictionary, so after copying the headers from the browser, you must manually add quotes, which is very troublesome.

At present, there is no related plug-in for this problem. The general solution is: use regular expressions to replace.

  1. Select the area that needs to be quickly quoted
  2. Hold down Ctrl + R (windows is ctrl + r) to fill in the regular matching expression
第一行[查找]: (.*?):(.*)
第二行[替换]: '$1':'$2',

3. Check the .* option to enable regular matching

4. Click Replace All: Replace all

The overall operation process is as follows:

9. The fastest way to select code blocks

Sometimes we need to select a code block to do some operations, which may be copying, deleting, or other behaviors.

Most people will use the mouse to drag the cursor to select, this method:

  1. Low precision, easy to select more or less;
  2. Slow speed, if the code block is longer, the efficiency will be much lower;

Here I recommend two methods for quickly selecting code blocks.

The first

By double-clicking the left blank area of ​​the code block with the left mouse button, you can quickly select it, and the effect is as follows:

the second

First shrink the code block, and then perform the selection operation:

Five, PyCharm  search and navigation

1. Where the precise search function is called

Search for places where this method is used in the project (Find Usage)

When you use Double + Shift to search who called a function in the whole project, you will find that there will be too much noise.

for example:

1. Some functions only include the function name and will be searched out.

2. Irrelevant file names and symbol names will also be searched. 

With such a lot of interference information, manually filtering out useless information will consume too much energy.

Because there will be a more precise way for the usage of the search function in all files.

The shortcut key is: Alt + F7

The effect is as follows:

  1. The function name will only be displayed if it matches exactly
  2. Only the place where it is called will be searched, and the place where it is defined will not be displayed 

Search for places where this method is used in the project (Show Usage)

The search content is no different from the first one above, but this display effect will be more intuitive:

  • The previous one: Displayed in a target tree, emphasizing the hierarchical relationship;
  • This one: it is displayed in a file list, which is more clear and easy to read;

The shortcut key is: Ctrl + Alt + F7.

In addition to using shortcut keys, there is an easier way, that is to directly press the middle mouse button:

Search for places where this method is used in the current file (Find Usage in File)

When you place the cursor on a function, all uses of that function will be highlighted. But as soon as you move the cursor away, the highlighting
will be disabled. If a class is very long and you cannot ensure that the mouse will not click elsewhere when you flip through the code, then this
highlighting method will not be very useful.

Here is a better way, that is to lock a function/variable in the highlighted state, the shortcut key is Ctrl + F7, and the shortcut
key to cancel the highlight is Ctrl + Shift + F7

The demonstration is as follows: 

2. Use bookmarks in the project to quickly locate

When I look at the source code of the framework, I most often use Ctrl + B (that is, Ctrl + left mouse button) to go deeper layer by layer, but when there are many source codes, the entire event process may involve more than a dozen Files and function calls are intricate. For a huge project, only a few key functions may be useful. Every time you want to find these functions, you have to search from the source function layer by layer. Trouble, I often make myself dizzy because of this.

Until later I discovered the bookmark function of Pycharm.

Using the bookmark function, I can put a bookmark in a key position, and when I want to read it, I can call the bookmark and quickly locate it.

To use it, you need to remember the following two shortcut keys

  • F11: Make or clear ordinary bookmarks;
  • Ctrl + F11: Make or clear bookmarks (with numbers, compatible with ordinary tags);
  • Shift + F11: Show all bookmarks;

At the position where you want to bookmark, press Ctrl + F11, you can add a serial number to this position, which can be a number or a letter. If you add a serial number of 1 to the position below, you can use Ctrl + F11 next time 1 jumps directly to this location.

Of course, you can also not add it, if you don't add it, it will be an anonymous bookmark. You can use Shift + F11 to display all bookmarks, and then jump.

At the same time, you can add a descriptive text to the bookmark, indicating what this code is:

I write the following information: 

Then use the shortcut key: Shift + F11 to list all bookmarks:

3. Search without dead ends: eight postures of search

Searching in source code is a very frequent operation.

According to the scope of the search, it can be divided into:

  1. Search in current file
  2. Search in global projects

Search in current file

To search in the current file, you can use two sets of shortcut keys, and their functions are equivalent:

  • Ctrl + F
  • Alt + F3

 In addition, according to the different search objects, it can also be divided into:

  • plain text;
  • method/function name;
  • class name;

Both method names and class names are symbols, and you can use the shortcut key Ctrl + F12 to call up the structure tree for searching.

Search in global projects

According to the search object, it can be divided into:

  1. file name
  2. class name
  3. method name
  4. Action name

Ordinary people use Double + Shift to search for everything (Search everywhere), including:

There are too many things to search, which means that the search cannot be precise.

In fact, for the above categories, PyCharm provides a special entry, let's start to introduce:

  • Precisely locate the file: shortcut key Ctrl+Shift+N 

  • Precise positioning to the class: shortcut key Ctrl+N 

  • Accurate positioning to symbols: all members of a class (functions, variables, etc.) can be called symbols, shortcut keys Ctrl+Alt+Shift+N 

  • Precise Search Action: Shortcut key Shift + Ctrl + A, for example, I search for all Actions in bookmarks below, and you can see that the corresponding shortcut keys are given out 

  • Accurately locate the file structure: The file structure includes classes, functions, and variables, which means that you can use this instead of the above method of locating classes and locating symbols. Shortcut key Ctrl+F12 

  • Search files under the specified folder: directly enter the file name you want to search in the project tree, if you want to clear the previous input, you can press esc to clear it. 

  • Search the project structure in the specified file: directly enter the structure name you want to search in the project structure (it can be a class, function, variable, etc.), if you want to clear the previous input, you can press esc to clear it. 

  • Precisely locate a certain line: the shortcut key Ctrl+G, as shown in the figure below, locate the 9th character in line 510. 

4. Filter test files when searching

Next, I will introduce one, a little trick when I look at the source code of the framework, which may only apply to a small number of people.


The framework I usually look at is OpenStack. I don't know what other frameworks are like, but there are a lot (really a lot) of unit test files in OpenStack . This caused me a lot of trouble when using Find in Path. You can feel it from the search results in the figure below. When searching for a function, there are many more results in the test file than in the normal file.

The search results of these test files are not only not helpful for us to see the source code, but more importantly, they also interfere with the line of sight.

So I researched it, starting from the file name, just fill in !test* in the File mask to filter out these test files.

The search results are much clearer at once:

5. Current file replacement and global replacement

There are two main types of replacements:

1. Replace in the current file, the shortcut key is: Ctrl + R

2. Replace under the global project, the shortcut key is: Ctrl + Shift + R 

6. Display the inheritance tree of the current class: Type Hierarchy

the first method

Use the shortcut key Ctrl + H:

The second method

Use the shortcut key Ctrl + O:

7. Display the call tree of the current method: Method Hierarchy

Press and hold the shortcut keys Ctrl + Alt + H:

8. Jump to the last edited place

Customizing functions based on open source frameworks is something I do every day.

Every time I write code somewhere, I may get stuck and have to go to other places to see the implementation of the code before I can continue writing.

It may be other codes in this file. After reading it, I have to come back and continue to write the original code, but in a file with thousands of lines, I have to jump back to the position where I just wrote the code. In fact, it is quite troublesome.

You can use the search function to search for the code you just made and jump, provided you remember your code.

You can also add a fixed comment to the original code, and just search directly at that time.

The above are relatively rigid, here is a better way.

You only need to press the shortcut key: Ctrl + Shift + Backspace, no matter where you are, whether it is in the same file or a different file, you can return to your last edited position, let me demonstrate below:

9. Quickly enter the parent class method in the subclass method

As shown below:

  1. The current cursor is in the reset method of the subclass;
  2. Press the shortcut key Ctrl + U to enter the reset method of the parent class;

10. Forward/backward to the last "click" place

The forward/backward here refers to the position where the cursor clicks.

There are three ways

Option 1: Use the Toolbar

First, let PyCharm display these two buttons, because you may not have these two buttons on your interface:

How to open this toolbar, see the picture below:

After setting the display toolbar, there will be the following two buttons on the interface:

Option 2: Use the menu bar 

The third way: use shortcut keys

Back: Go back to the last cursor position, Alt + Ctrl + ←

Forward: Back to the last cursor position, Alt + Ctrl + → 

11. Display recently opened files

If you close a file tab and want to open it later. It is more troublesome to search and open one by one in the project tree.

Try the shortcut key: Ctrl + E, you can directly call up the file you have opened, or even click the button below to select the modified
file.

12. Do not use the mouse, operate the directory to open the file

In the case of hiding the directory tree, if you want to switch to an unopened file, you can try the shortcut key: Alt + Home:

  • ← : enter the parent directory
  • →: enter the subdirectory
  • ↑: Open the directory and display all files in the directory
  • Enter: enter the selected directory, or open the selected file

13. Quickly jump to the line with ERROR

I opened PyCharm a few days ago and found that there are many wavy lines in the navigation bar. Students who have experience in using PyCharm will know that this is an error in the code.

Following the wavy line, I expanded the directory tree layer by layer, and finally found the file that contained the error. Because it was a mistake, I don't know
which line I changed. After reading this file, there are nearly 8,000 lines of code. Should I look for it line by line?

When you encounter a problem, you should try to find a shortcut. Is there a way to locate the error code at once?

At this time, I remembered that PyCharm provides us with a Keymap panel, which can easily set and query shortcut keys.

Maybe I can find the answer I want there

I entered Error in the search box, and I found the shortcut key F2 and Shift+F2 to quickly locate the error line to quickly locate the error line. 

Use the shortcut key F2 to check it turns out that there is a problem with the indentation here: 

There is another corresponding shortcut key: Shift + F2

F2: Jump to the next line with errors.

Shift + F2: Jump to the previous line with errors.

14. Jump to the previous/next method

The shortcut key for PyCharm's native jump to the previous/next method is:

  • Alt + ↑ : jump to the previous method
  • Alt + ↓ : Jump to the next method 

15. Switch tabs left/right

The shortcut key for PyCharm to switch to the left/right tab page natively is:

  • Alt + ← : Switch to the tab on the left
  • Alt + → : switch to the right tab

16. Quickly open the available toolbar for files

Use the shortcut key: Alt + F1

A window will pop up, which will show which tool windows are available for the file, use the arrow keys to select.

17. Learn to jump code blocks across levels

According to the position of the code block in the module, the code block can be divided into:

  1. line code block:
  2. flow control block
  3. function code block
  4. function block
  5. class code block

How to realize the jump of cross-level code blocks (from the next level to the previous level, irreversible) in PyCharm?

Just remember this set of shortcut keys:

  • Ctrl + [: Jump to the beginning of the previous code block;
  • Ctrl + ]: Jump to the end of the previous code block;

18. Make good use of TODO to record to-do items

Usually when someone interrupts me, ask the other party to give me a minute, and use PyCharn's TODO function to quickly record the current state of mind and what to do next.

The method of use is similar to that of comments, as long as it must start with TODO.
Then, when you want to view all TODO items in the global project , you can use the shortcut key to bring up the TODO panel. Shortcut key: Alt+6.

In addition, I also use this to record the code logic to be optimized and the functions to be added in the next version.

If it is a relatively urgent BUG, ​​you can use a TODO-like mark — FIXME to distinguish the degree of urgency. 

19. Find recent search records

In the file search or in the global search box, use the shortcut key alt + ↓ to view all recent search records.

Six, PyCharm  version and management

1. Use Git for version management

Turn on version control

Click VCS -> Git -> Clone:

Fill in the relevant information of the git warehouse:

Click Test, it will try to connect to the git server, and you will be asked to enter the login account and password in the middle. 

After clicking OK, if everything is normal, it will prompt that the connection is successful. 

After clicking OK, PyCharm needs you to choose how to open this Git warehouse directory, open in the current window, or create a new window?

Since I will have multiple Git repositories under one PyCharm, for convenience, I choose to open in the current window (note that
Add to currently opened projects is checked). 

At this point, Git configuration is complete.

At this point, you can check VCS -> Git, and find that all the buttons that were grayed out before can be used. 

If you want to modify the configured Git repository, you can click File -> Setting -> Version Control to bring up the following interface. 

I have to say that the UI of PyCharm can do a good job, just change something and submit it:

Shortcut keys related to VSC

Ctrl + K: Submit the code to the version controller;

Ctrl + T: update code from version controller;

Alt + Shift + C: View recent change records;

Alt + `: Quickly pop up the version controller operation panel;

Ctrl + Shift + ` : operation branch;

Ctrl + Shift + K : Push to remote;

2. Modification of three viewing files

If your project is under the management of git, after you modify the file, you will have many ways to check what you have modified
?

The first of course is to use git diff:

The second is to use the show history written before:

The third method, which I will introduce today, is the easiest and most direct method.

In the position where there is a text change, PyCharm will have a prompt, as marked by the red arrow below, click it to view it directly, and quickly roll back. 

3. The difference comparison function comparable to beyond compare

Among the necessary artifacts for program development, beyond compare can definitely rank first.

Although it is easy to use, this thing is charged.

If it is a simple comparison of a single file, you can actually use the one that comes with PyCharm.

Click the source file, then click View -> Compare With … -> select the target file.

For a comparison example, you can check the picture below, the UI is pretty good.

4. View file modification records: Annotate

When your project is in a controlled state (version control is turned on), your modifications to the files in the project will be recorded.

So how to check these records?

Right click on the left side of the edit box and select Annotate:

The interface as shown in the figure below will appear. 

This interface records who modified which line of the file on which day, and what is the commit number?

It is very convenient for us to trace the code. 

5. View all operation records of the file

In order to restore the grammatical error caused by hand error, I used shortcut keys to locate the wrong line. Although the problem was solved, I always felt that the
posture was wrong. What if there was no grammatical error? How do I trace back to where the change was affected?

If there is a way to view the latest modification records of the project (without git for version control), that would be great.

Coincidentally, today I opened PyCharm and pushed me this tip. Use Alt + Shift + C to quickly view the recently modified content:

Seven, PyCharm  plug-ins and tools

1. Use vim in PyCharm

In most scenarios, the efficiency and accuracy of using the mouse is far inferior to keyboard shortcuts (provided that you have
mastered the shortcuts quite proficiently), you have to admit it.

Vi can meet all your needs for text manipulation, and it is more efficient and geek than the visual interface. If you are like me, you are a loyal vim fan. After installing Pycharm, we will definitely install the ideaVim plug-in as soon as possible, which allows
us to use vim to edit code in Pycharm.

The installation method is as follows. After the installation, you need to restart Pycharm to take effect.

2. JetBrains officially launched the Sinicization plug-in

I often hear many beginners complaining, why is PyCharm all in English? It is so difficult to learn.

In the past, I would tell them that learning a programming language, English is a very important ability, you must not be afraid of it, avoid it, but if you learn it and adapt to it,
if you can't even adapt to an IDE, then Stop learning to program.

And now, JetBrains officially released a Chinese plug-in, the name is: Chinese, searched in the plug-in market, it ranked first, and the download volume has already reached 400,000. Compared with the second-ranked folk Chinese plug-in, it is simply not an order of magnitude. of.

After clicking INSTALL to install, you will be prompted to restart to take effect. 

After the reboot is complete, what we are presented with is a familiar yet unfamiliar interface, and all the menu bars have been changed to Chinese. 

Clicking into the settings, it can be said that the localization has been basically realized, leaving only a small amount of English (is it because these words are easier to understand if they are kept in English than after
translation sockets and sockets.), However, I personally feel that it does not affect the use at all. 

3. Write Markdown in PyCharm

Rich text typesetting documents is a very painful thing. For programmers to write documents, the best recommendation is to use Markdown. All my
blog diaries are written in Markdown.

The code downloaded from Github generally has a README.md file, which is a Markdown file.

PyCharm does not install the Markdown plug-in by default, so it cannot display text in Markdown format, and displays the original text.

Therefore, if you want to read Markdown documents in PyCharm, you can install the Markdown support plugin.

There are two ways to install:

  1. The first, the most convenient, is that you open an MD file, and PyCharm will prompt you to install it.
  2. Search and install from the plugin store.

The effect is as follows:

4. Regular expression test: Regex Tester

Regex Tester is a third-party plugin for PyCharm that can test regular expressions.

Follow the entry in the figure below to install the Regex Tester plug-in:

After the installation is complete, there is no need to restart PyCharm, just click the small rectangular button at the bottom left of the PyCharm interface to find the Regex Tester option. 

After clicking Enter, the following interface appears. I casually wrote a regex that matches mobile phone numbers (not necessarily accurate), and the background of the matched string
will be highlighted. There are also some options on the upper right, such as case sensitivity, multi-line mode, etc., which can be selected according to needs.

Regex Tester also provides Split, Replace functions, etc.

The effect is as follows: 

5. Using Bash commands on Windows

There are many differences between the cmd command on Windows and the Linux command. For example, to list all files in the current directory,
use dir on Windows, but ls -l on Linux.

For developers like me who are familiar with Linux, the bad experience brought by those CMD commands in Windows is unbearable
.

 

In the pop-up Bash window, you can type the Linux command you want to use, isn't it much more comfortable. 

6. The code is not standardized, automated PEP8

pep8 is a coding specification for the Python language. If you are a novice and you just want to quickly grasp the basics and don't want to pay too much
attention to the writing style of the code (although this is very important), then you can try this tool - autopep8

First, install this tool in the global environment (do not install it in a virtual environment).

$ sudo pip install autopep8

Then import this tool in PyCharm, the specific settings are as follows:

Name: AutoPep8
Description: autopep8 your code
Program: autopep8
Arguments: --in-place --aggressive --aggressive $FilePath$
Working directory: $ProjectFileDir$
Output filters: $FILE_PATH$\:$LINE$\:$COLUMN$\:.*

I randomly wrote a piece of code that does not conform to the pep8 specification:

Right-click and select External Tools -> AutoPep8: 

Take a look at the effect, it is quite obvious:

You may say that Pycharm itself has this function. The shortcut key Command + Option + L can realize one-key pep8. You can compare, Pycharm's built-in code pep8 function is not as thorough as this autopep8. I believe your final choice must be the latter. 

7. HTTP interface debugging: Test RESTful Web Service

PyCharm's Test RESTful Web Service tool provides a RESTful interface test interface, as shown in the figure below, provides http methods such as get, post, and put, among which the Request sub-interface headers, Parameters, Body and other functions, and the Response sub-interface is used to display the return Value, Response Headers is used to display the returned message headers.

To demonstrate, I first use Flask to write an HTTP interface:

from flask import Flask, request

app = Flask(__name__)

@app.route('/hello')
def index():
    name = request.args.get('name')
    return '֦অ҅ ' + name

if __name__ == '__main__':
    app.run()

And run it to start the service, the access address is: http://127.0.0.1:5000/:

Open the Test RESTful Web Service as shown below:

The following interface will appear, fill in the following information in the red box:

Then click the run button on the far left to send an http request to the server. 

8. Select execution: Execute Selection in Console

When you want to write a simple test code, maybe you will like this:

  1. Write directly using the Python Shell. The downside is that there is no auto-completion.
  2. Open a new file in PyCharm. The disadvantage is that you need to create a new file and delete it when you are done.

Today I will introduce a new method to you, which can completely avoid the shortcomings of the above two methods.

That is Execute Selection in Console, which can be said to be Run in Anywhere.

Just write the code in the current file, then right-click Execute Selection in Python Console or use the shortcut key option + shift + E (alt + shift + E on windows) after the cursor is selected.

Then PyCharm will pop up a Python Console window, and then run the code you selected. 

One of the bright spots can be found, that is, using this method, PyCharm will automatically handle the indentation for us (when we choose, there is indentation in front, but when executing, it will automatically remove the extra indentation in front) 

9. One-click code performance analysis

There are many modules in Python that can help you analyze and find out where performance problems occur in your projects.

For example, the commonly used module is cProfile, and in some frameworks, there are also built-in middleware to help you perform performance analysis, such as Django and WSGI.

As the first IDE for Python, PyCharm itself supports this feature. And it is very convenient to use, Xiaobai.

Suppose you want to analyze the performance loss of the following code to find out which function takes the most time:

import time

def fun1():
    time.sleep(1)

def fun2():
    time.sleep(1)

def fun3():
    time.sleep(2)

def fun4():
    time.sleep(1)

def fun5():
    time.sleep(1)
    fun4()

fun1()
fun2()
fun3()
fun5()

 Click Run -> Profile 'Program' to perform performance analysis.

After running, a performance statistics interface will pop up automatically. 

The performance statistics interface consists of Name, Call Count, Time(ms), Own Time(ms), and 4 columns form a table, as shown in the figure below.

  1. The header Name shows the called module or function; Call Count shows the number of calls; Time(ms) shows the running time and time percentage, and the time unit is milliseconds (ms).
  2. Click the small triangle on the table header to sort the table in ascending or descending order.
  3. Double-click a row in the Name column to jump to the corresponding code.
  4. Take the line fun4 as an example: fun4 is called once, and the running time is 1000ms, accounting for 16.7% of the entire running time

Click the Call Graph (call relationship graph) interface to visually display the direct call relationship, running time and time percentage of each function, as
shown in the figure below. 

The 4 buttons in the upper right corner indicate zoom in, zoom out, true size, and appropriate size;

  1. The arrow indicates the call relationship, from the caller to the callee;
  2. The upper left corner of the rectangle displays the name of the module or function, and the upper right corner displays the number of calls;
  3. The running time and time percentage are displayed in the middle of the rectangle;
  4. The color of the rectangle indicates the trend of running time or time percentage: red > yellow-green > green. It can be seen from the figure that the rectangle of fun3 is yellow-green and fun1 is green, and the running time of all fun3 is longer than fun1.
  5. It can be seen from the figure that Test.py directly calls the fun3, fun1, fun2 and fun5 functions; the fun5 function directly calls the fun4 function; fun1, fun2, fun3, fun4 and fun5 all directly call the print and sleep functions; the entire test code The total running time is 6006ms, among which the running time of fun3 is 1999ms, accounting for 33.3% of the time, that is, 1999ms /6006ms = 33.3%. 

10. Enable static code analysis check

For compiled languages, such as Java, the code needs to be compiled into a machine-recognizable language before it can run. During the compilation process, the correctness of the program can be checked by analyzing or checking the syntax, structure, procedures, and interfaces of the source program. performance, find code-hidden errors and defects. This process is called a static code analysis check.

For an interpreted language such as Python, the code is translated while running, and there is no need to go through the process of compiling. Many
errors that cannot be seen by the naked eye at once can only be found by running (anyway, it is so convenient to run).

Since Python is so easy to run, we don't need to pay much attention to static analysis tools.

But that's not to say that static analysis tools are completely useless, I think there are still.

If your coding ability is not very mature, there may be many hidden bugs in the code. Since Python is only interpreted
when , only one error can be found in one run. To find 100 bugs, you need to run 100 Again, the numbers are a bit exaggerated. In
fact, I want to say that if so many errors can be found through a static inspection and corrected immediately, the efficiency of development and debugging can be improved
. Of course, not all errors can be found in advance through static analysis, I hope you will not misunderstand this point.

As the most powerful IDE for Python, PyCharm itself has this function built in and does not require you to install any plug-ins.

You only need to click on the project folder as shown below, then right click and select Inspect Code to enable static inspection.

My static inspection of the open source component nova found thousands of irregularities. 

11. Run Jupyter Notebook in PyCharm

Before using Jupyter, it must be installed:

$ pip install jupyter

Then follow the instructions in the figure below to create a new Notebook, and you can start working.

This interface feels inconsistent with Jupyter's style:

But there is no difference in use, just remember the three shortcut keys (the following refers to the ones on Mac, and the ones on Windows are different):

  • Ctrl+Enter: run the cell
  • Option + shift + ↩: debug the cell
  • Shift + ↩: Insert a new cell

As long as you have installed Jupyter, you will automatically change to Jupyter mode when you use Python Console:

12. Shortcut key management master: Key Promoter X

If I were to recommend a must-install plugin for PyCharm to novices, it must be Key Promoter X.

It is equivalent to a shortcut key management master, it is always in:

I urge you, which shortcut operation should you use to improve efficiency in your current operation?

Remind you, you haven’t set a shortcut key for this operation at the moment, set one up now?

With Key Promoter X, you will be able to master the shortcut keys proficiently in no time, and the replacement of the mouse is just around the corner.

For example, if I use the mouse to open Find in Path, it will pop up a window in the lower right corner to prompt you which shortcut key to use.

13. Code scrolling preview: CodeGlance

If you have used Sublime Text before, switching to other code editors will be more or less unaccustomed, because few editors
will have a scroll bar with a preview function like Sublime.

In PyCharm, there is no problem that cannot be solved. If there is, then install a plug-in.

To use this preview scroll bar in PyCharm, just install the CodeGlance plugin.

The effect is as follows:

14. JSON beautification plug-in: Json Parser

In the development process, I often check whether a string of JSON strings is legal. In the past, my practice was to open the online website https://tool.lu/json/ and directly beautify it for verification. Only the JSON format is available. What is correct and legal can be beautified.

It wasn't until later that I found out that there is a plugin in PyCharm dedicated to doing this, that is JSON Parser, after installing it in the plugin market
, restart PyCharm, and you can see it in the right sidebar. 

15. Use PyCharm for SSH remote login

Developers usually have their own software for ssh remote login, such as Xshell.

For friends who often need support from the ssh server, it is undoubtedly the best choice to choose professional software, but for those
friends who do not use it frequently, in fact, only PyCharm is enough.

1. SSH remote server

Click Tools -> Start SSH Session, the following options pop up, select Edit Credentials...

Enter the host information and click OK: 

The connection is successful. 

Opening the connection through the above cannot be saved, and you still need to manually enter the ip port password next time you run it.

If you want to save the connection information of ssh, you can add it in the following location:

After adding it here, you can see it in Tools -> Start SSH Session:

2. SSH to the Vagrant virtual machine

If your current project has already configured the Varant environment, logging in will be more convenient.

Use Vagrant to build a one-and-done development environment:

Go directly to the Vagrant virtual machine for this project:

Eight, PyCharm  commonly used skills

1. Easy to implement JSON formatting

The following is an unbeautified json file. When a json file has a lot of content, it is
very difficult to extract effective information from it without re-beautifying it with tools.

In the past, I often used some online websites, such as: online code formatting

Hold down Ctrl+Alt+L and it looks like this after beautification.

2. Accidentally deleted items can be retrieved in one second

Once, due to my own misoperation, I deleted a project I wrote for two weeks without any backup.
When I look back, I can't even remember when I did the deletion.

As an old driver, of course, I opened the recycle bin fearlessly and searched. The recycle bin that has not been cleaned up for several months
is really a mess. There are all kinds of jpg and avi, which is unsightly.

I took a quick look at it for a minute, but I didn't find the few py files I was looking for. I thought to myself, there should be too many files, and I saw that the
fork was broken. Since the project was written recently, I still remember the file name clearly. Since there is a file name, I used the
search function that comes with windows, but there was still no result. Only then did I realize the seriousness of the situation. The file may be real. "Gone".

I haven't cleared the recycle bin for a long time, why are there no files in the recycle bin?

I think this may be an unusual delete. Could it be a delete operation initiated in Pycharm, and will it not be
thrown into the recycle bin? After some testing, I really couldn't find it in the recycle bin, but this attempt also accidentally discovered
a hidden function of Pycharm, Local History, which will save all your operation records on files.

Take the file I just tested as an example. I first created a new file, and then added a few lines of code to this file.
In the end I deleted this file.

At this point, you can right-click in your project directory, there is an option for Local History, and then click the sub-option
Show History, and you can see that there is a record board here. If you want to restore the deleted file, right-click on the deleted record item
and select Revert to restore it.

3. Smart completion, ignoring case

Smart search completion is one of the most attractive features of the IDE.

When your object starts with a capital letter, and you use lowercase letters to write the code, you cannot find the function, you must first switch to uppercase and enter it again
.

How to avoid this embarrassing situation?

Just turn off case matching in the configuration. 

The effect is as follows: 

4. Block editing in columns

Let me give you a small question first, like the following code, what if you can quickly delete the comments behind the following code without affecting the code
?

There are two methods I can think of. If there are regular comments like the above, you can use regular matching + replacement to achieve. 

For this scenario, I thought that vim can be used to easily solve it. Vim supports block editing. You can select an area in units of columns and then
perform operations. This is a very common uncommenting operation in vim.

Also come back to PyCharm, you will find that it also supports block editing.

If you are using an old version of PyCharm, when you hold down alt, and then use the mouse to select, you will find such a magical
thing. 

If the shortcut key above does not work, it means that your PyCharm is an old version. In the newer version, there are two ways to open the column selection
mode

  1. Use the shortcut keys Alt + Shift + Insert
  2. Right click and select "Column Selection Mode"

In the new version, the column selection function has become a mode, which can only be used after it is turned on, and needs to be turned off after use. Compared with the old version, I personally think that this change is not good and cannot be used immediately. 

5. Six ways to read source code

When you use a function of a module, if you want to view the source code of this function, there are two ideas.

first thought

Enter the position of the function declaration, and you can see the source code.

The corresponding shortcut keys are as follows:

  1. Ctrl + B:Go to Declaration or Usages
  2. F4:Jump to Source
  3. Ctrl + Alt + B :Go to Implementation(s)
  4. Ctrl + left mouse button

second thought

A small window pops up on the current page to directly display the source code without jumping to another page like the above.

The shortcut key is: Ctrl + Shift + I:

6. Quick refactoring, modify all functions and variables

When a colleague resigns to hand over the code, sometimes he will silently complain in his heart.

For the convenience of later maintenance, I usually spend a few days doing a lot of refactoring of its code.

variable renaming

When refactoring code, it is inevitable to rename variables.

If you change them one by one, it is obviously not very smart. You must know that we are using an IDE. You may say, can’t just replace them all with search
? It really doesn't work.

For example, in the following code, I only want to change the test_name in myfun, but the global variable with the same name should not be modified
. If you replace globally, there will be fratricide.

At this time, how do we do it?

You can use PyCharm's Refactor function, which will automatically match the scope, so that it can be changed in batches without accidental injury.

The operation method is very simple, first select your variable, and then use the shortcut key Shift+F6 to rename it directly. 

function renaming

If it is to rename the function, it is also possible to use Shift + F6, but there are many points.

A more appropriate method is to use Command + F6, the demonstration process is as follows:

7. Tabs and spaces are mixed and automatically converted

In teamwork, you will inevitably move files edited by others. Some people like to make tabs for indentation, and some people like to use four spaces
for indentation.

But in the same Python file module, the two styles of tab and four-space indentation cannot coexist. This requires you
to code according to the original indentation style of the file. In Pycharm, you can set the automatic detection of the indentation style of the original file to determine whether it
is TAB or four spaces when you use the tab key to indent.

Tick ​​the icon to enable automatic detection.

The above is how to determine the indentation of the current edit when modifying an old Python module.

For new modules, how is the default indentation method determined?

As shown in the figure below, if you tick Use tab character, after you create a new Python, TAB will be used for indentation, otherwise, four spaces will be used for indentation. 

8. Code area selection without the mouse: Extend Selection

According to the size of the selected area, it can be divided into:

  1. selected word
  2. selected expression
  3. Select a single row
  4. Select code block
  5. Select function
  6. Selected class

For the code area, it is usually completed with the help of the mouse. Here I recommend a set of shortcut keys for you to select the area without the mouse
:

  • Ctrl + W): expand the selected area;
  • Ctrl + Shift + W: shrink the selected area;

The effect of the demonstration is as follows:

This usage applies to:

  1. People who use mac notebooks, do not use a mouse, but only use a touchpad;
  2. People who want to select a class or function with thousands of lines and perform operations;

9. From the visual Python package manager

After PyCharm configures the interpreter, all installed packages in your environment will be listed below.

On the right there are four buttons:

  1. Install
  2. uninstall
  3. upgrade
  4. view earlier version

You can manage these packages through them.

Let's take installing the parse package as an example:

Click the + button:

Search for parse and click on the lower right corner to install: 

Return to the package management interface, and the installation has been successful. 

10. Quickly move/copy files: F6/F5

When you want to drag a file to another directory, there are two operations for normal people:

  1. Drag and drop directly (I personally feel that this is the most convenient)
  2. cut first, then paste

PyCharm has a more convenient entry for this kind of refactoring operation.

Just press and hold F6 and a Move Module window will pop up, just select the target directory directly.

In addition to moving, copying is also possible. The shortcut key has changed to F5. 

11. Display class inheritance diagram: Show Diagrams

When reading some relatively large projects, if the inheritance relationship of the class is more complicated, it will bring a lot of obstacles to our reading source code.
Faced with this situation, the following technique will come in handy.

In the class you want to view the inheritance relationship, right click and select Diagrams -> Show Diagram:

A new window will be added, using UML to show you the inheritance relationship of the class.

12. Quickly hide the project tree

When you use the small screen of the notebook to write code, the project tree on the left will show a special space.

Usually people will manually hold the mouse to click the leftmost button or click the minimize button. like this:

But in fact, there are other better ways, double-click the tab, you can hide it. 

13. Set the file to read-only: Read-Only

If you are worried about the code being accidentally modified by yourself, you can set the file to read-only.

The method is very simple, just click ੜᲁ in the lower right corner to lock the file.

After locking, when you want to edit, the following window will pop up.

As long as you click OK above, you are ready to edit.

Because this function is limited, it can only be used as a reminder, and there is no way to enforce it. 

14. Automatic import to resolve dependencies: Alt+Enter

When you use a function in a certain package, you generally need to import the package before you can use it.

With PyCharm, how easy is it? It can automatically find the package that the function may belong to according to your function, and it can be automatically imported after your
confirmation.

The shortcut key to find is Alt + ↩.

The final usage effect is as follows:

15. Three ways to open folders in file manager/Finder

the first method

Right-click and select Reveal in Finder (under Mac) or Show in Explorer:

The second method

When you use the file opened by Ctrl + Shift + N, you will find that in the project tree on the left, the directory of the file has not been
expanded . At this time, you want to use ᒫӞᐿොဩ to open it in the resource manager or Finder , you must first open the sidebar of the project tree
, click on the directory of the file layer by layer, and then Reveal in Finder.

In fact, there are better solutions to this embarrassing situation.

Please see the picture below: When the left sidebar is not open, first press Ctrl + Shift + N to find the file and open it, then hold down Ctrl and click with the mouse, all parent directories of the file will appear, use ↑ or ↓ to select Select, and finally press Enter to
open it in Finder or Explorer. 

third method

It's the fastest, easiest, and the only way to do it without using a mouse.

Use the shortcut key: Alt + F1 

16. Open the folder in Terminal

Maybe you do this when you want to open a project's folder in Terminal.

the first method

First copy the absolute path, then open the terminal and paste the path into:

The second method

PyCharm directly integrates Terminal for us, we can click directly to enter:

Nine, PyCharm  database operation

1. Connect to MySQL

In PyCharm, you can connect to most of the mainstream databases on the market, such as MySQL, MongoDB, etc. For most people, there is no need to download Navicat after having PyCharm.

Taking MySQL as an example, explain how to create and save a database connection.

First click Database in the right sidebar of your PyCharm, then click the + sign in the upper left corner -> Data Source -> MySQL.

The following interface pops up, after entering ip, port, password and other information, click Test Connection to test whether the connection can be made, if yes, click OK to save for reuse next time. 

If there is a prompt to download the driver in the lower left corner, just click to install it~

After the connection is successful, a MySQL Console query interface will pop up automatically, and you can run SQL commands in this interface. 

2. Switch database

When writing sql statements in the Console, you don’t need to use use <db> to select the database. Mysql is selected by default.
If you want to switch databases, you can click the location as shown below to switch.

3. Query result formatting

form

The query results are printed in the form of a table by default, and you can easily copy them to Excel:

JSON format

If you need to display the result in JSON format, click to switch to Tree:

CSV format

If you need to display the results in CSV format, click to switch to Text:

4. Data export

PyCharm not only provides the function of data export, but also does it almost to the extreme. It supports export in various formats: csv, xlsx, json, html, xml, sql, etc. 

The following will show you one by one.

Export to csv or xlsx format, convenient for secondary processing:

Export as SQL statement, which is convenient for restoring data: 

Export JSON or xml for other purposes such as sending network requests: 

Export as Markdown, which is convenient for Markdown typesetting display: 

Export as HTML, convenient to use browser to display data: 

Guess you like

Origin blog.csdn.net/qq_35029061/article/details/130182165