Wechat search public account: Python Geek column. Share different Python dry stuff every day

PyCharm is a Python IDE that helps programmers save time and increase productivity. So how to use it? PyCharm installation, plug-ins, external tools, and professional features are all covered in this article.

The Heart of the Machine

PyCharm has not been systematically introduced before, but how to configure the environment, DeBug, synchronize GitHub, etc., is probably learned through experience or trial and error. In this article, we will not provide a complete guide, but we will introduce some of PyCharm’s most important abilities, which we will need to learn in practice.

Heart of the Machine readers should be well aware of PyCharm, developed by JetBrains, which is almost the most commonly used IDE for Python. PyCharm saves us a lot of time by managing code and doing a lot of other tasks such as debugging and visualization.

This article will introduce:

PyCharm installation

Write code in PyCharm

Run the code in PyCharm

Debug and test your code in PyCharm

Edit existing projects in PyCharm

Search and navigate in PyCharm

Use version control in PyCharm

Use plug-ins and external tools in PyCharm

Use PyCharm Professional features such as Django support and Science mode

This article assumes that you are familiar with Python development and have a version of Python installed on your computer. This tutorial will use Python version 3.6, with screenshots and demos from macOS. Since PyCharm works on all major platforms, readers will see slightly different UI elements on other systems and may need to tweak some commands.

PyCharm installation

This article will use PyCharm Community Edition 2019.1, which is free and available on all major platforms. Only the last part, PyCharm Professional Feature, is PyCharm Professional Edition 2019.1.

PyCharm is recommended to be installed with the JetBrains Toolbox App. Using the App, you can install different JetBrains products or versions of the same product, and update, roll back, and easily remove any tool if necessary. You can also quickly open any project in the right IDE and version.

Toolbox App installation guide, see JetBrains official documentation: www.jetbrains.com/help/pychar…

The App will provide appropriate installation instructions depending on your operating system. If it does not identify the system correctly, you can find the appropriate system in the drop-down list in the upper right corner.

After successful installation, start the app and accept the user agreement. Under the Tools option, you can see a list of available products. Find PyCharm Community from there and click Install.

Now PyCharm is installed on your machine. If you don’t want to use the Toolbox app, you can install PyCharm separately.

Start PyCharm and you will see the import Settings popup. PyCharm automatically detects that this is the first installation and selects the “Do not Import Settings” option for you. Click OK and PyCharm will let you select the keymap scheme. Keep the default Settings and click on “Next: UI Themes” in the lower right corner:

PyCharm will ask to choose Darcula or Light mode. You can choose your preferred mode and click “Next: Launcher Script” :

This tutorial will use Darcula in dark mode.

On the Next page, just leave the default Settings and click “Next: Featured Plugins,” and PyCharm will show you the list of available plug-ins. Click “Start using PyCharm” and now you can write code!

Write code in PyCharm

In PyCharm, you can perform any action in the “project”. So first you need to create a project.

After installing and opening PyCharm, you will see the welcome page. Click “Create New Project”, the “New Project” popup window appears:

Specify the Project location, open the Project Interpreter list, and choose to create a new Project Interpreter or use an existing one. Select “New Environment Using” to open the drop-down list to the right of it and select Virtualenv, Pipenv, or Conda. These tools allow you to create separate Python environments for different projects to store the dependencies needed for different projects.

You can choose either of these. This tutorial uses Virtualenv. Once selected, specify the environment location and select Base Interpreter to install on the system from the List of Python interpreters. In general, just keep the default Settings. There are two checkboxes: inherit the global package environment in the new environment, and make the current environment available to all other projects, and do not select either.

Click “Create” in the lower right corner to Create a new project:

A “Tip of the Day” popup appears on the screen and PyCharm provides trick on each startup. Close the popover.

Now we can start our new Python program. If you’re on a Mac, use Cmd+N. If you’re running Windows or Linux, use Alt+Ins. Then select Python File. You can also select File → New from the menu. Name the new file guess_game.py and click OK. You will see the following PyCharm window:

As for the test code, let’s quickly write a simple guessing game, in which the program selects a number and asks the user to guess. At each guess, the program tells the user whether the number he guesses is larger or smaller than the mystery number. The game ends when the user guesses the number. Here’s the code for the game:

Type the above code directly instead of copying and pasting. You should see the following screen:

As shown above, PyCharm offers Intelligent Coding Assistance that performs code completion, code checking, error highlighting, and quick fix suggestions. For example, type main and hit TAB. PyCharm completes the entire main clause.

Also, if you forget to type if before the conditional, add. If at the end of the sentence and click Tab. PyCharm will repair the if conditional. The same applies to True. While. This is the Postfix Completion function of PyCharm, which helps reduce the number of backspace key uses.

Run the code in PyCharm

Now that you’ve coded the game, you’re ready to run it.

The game program runs in three ways:

1. On a Mac OS, press Ctrl+Shift+R. On a Windows OR Linux OS, press Ctrl+Shift+F10.

2. Right-click the background and choose Run “Guess_game” from the shortcut menu.

3. Since the program has a __main__ clause, you can click on the small green arrow to the left of the __main__ clause and select “Run” guess_game “.

Run the program in either of these ways, and a Terminal pane appears at the bottom of the window showing the output of your code:

You can play the game and see if you can guess the numbers. (Pro tip: Start at 50.)

Debug your code in PyCharm

Did you find the mystery number? If you do, you might see something strange: instead of printing a congratulatory message and displaying an exit button, the program starts over. That’s the bug. To find out why the program is restarting, you need debug.

First, click on the blank area to the left of line 8 and set a breakpoint:

A breakpoint is a line where the program automatically stops, and you can explore what’s wrong with the code after the breakpoint. Next, start debugging in one of the following three ways:

1. On a Mac OS, press Ctrl+Shift+D. On a Windows OR Linux OS, press Shift+Alt+F9.

2. Right-click the background and choose Debug guess_game from the shortcut menu.

3. Click the small green arrow to the left of the __main__ clause and choose Debug “guess_game”.

After that, you should see the Debug window appear at the bottom:

Follow these steps to execute program debug:

1. Notice that the current line is highlighted in blue.

2. The Debug window displays random_int and its value. Record the number. (The figure above is 85.)

3. Click F8 to execute the current line of code and proceed to the next line of code. If necessary, you can also use F7 to jump to functions in the current line. As you continue to execute the statement, variable changes are automatically displayed in the Debugger window.

4. Notice that there is a Console label on the right of the Debugger label. Console labels and Debugger labels are independent of each other. You can interact with programs in the Console and perform debug actions in the Debugger.

5. Switch to the Console TAB to start the guessing process.

6. Type the number displayed in the left Debugger TAB and press Enter.

7. Go back to the Debugger label.

8. Click F8 again to evaluate the if statement. Notice now you’re on line 14. Why not line 11? Because the if statement on line 10 evaluates to False. So why does it work out to be False when you type in the number?

9. Look closely at line 10 and notice that we are comparing user_guess with an incorrect item. We should compare the user’s guess with random_int, but here we compare randINT (the function imported from the Random package).

10. Change randINT to random_int and repeat the same steps to restart debug. You’ll notice that this time you get to line 11, and line 10 evaluates to True:

Congratulations, the bug has been fixed!

Test the code in PyCharm

No application is reliable without unit testing. PyCharm can help you write and run unit tests quickly and comfortably. By default, UnitTest is used as a test runner, while PyCharm also supports other testing frameworks such as PyTest, Nose, DocTest, Tox, and Trial. For example, you can select the PyTest test runner for your project by following these steps:

1. Open the Settings/Preferences → Tools → Python Integrated Tools dialog box.

2. Select PyTest in the default test runner field.

3. Click OK to save the Settings.

The examples in this tutorial will use the default test runner, UnitTest.

In the same project, create the file Calculator.py and put the following Calculator classes into the file: calculator

PyCharm makes it easy to create tests for existing code. Open the calculator.py file and perform any of the following steps:

On Mac, press Shift+Cmd+T. On Windows or Linux, press Ctrl+Shift+T.

Right-click the background of the class and choose Go To and Test.

Navigate → Test in the main menu.

Select Create New Test… , get the following window:

Keep the default Settings for Target Directory, Test File name, and Test Class name. Select the two methods you want to test in the image above and click OK. All right! PyCharm automatically creates the file test_Calculator.py and creates the following stub tests in it:

Run the test using any of the following methods:

Use Ctrl+R on a Mac, Shift+F10 on Windows or Linux.

Right-click on the background and select “Run” Unittests for test_calculator.py “.

Click the small green arrow to the left of the test class name and select “Run” Unittests for test_Calculator.py “.

You should see the tests window appear at the bottom with all tests failing:

Notice the hierarchy of test results on the left and the output of the terminal on the right. Now change the code to the following to implement test_add:

Rerun the tests and you will see that one test passes and the other fails. Explore different options to show passed and ignored tests, sort tests alphabetically, and sort tests by duration by:

Note that the sleep(0.1) method in the figure above is used to slow down one of the tests so that the tests can be sorted in time.

Edit existing projects in PyCharm

Single-file projects are great as examples, but you usually need to deal with larger projects. This section shows you how to use PyCharm to process larger projects.

To explore the project-centric nature of PyCharm, you will use the Alcazar Web framework (which is used for learning purposes). In the local copy the repo (address: realpython.com/optins/view…

When you already have a project locally, open the project in PyCharm using one of the following methods:

From the main menu, click File → Open.

Click Open on the welcome page.

After that, find the folder containing the project on your computer and open it.

If the project contains a virtual environment, PyCharm automatically uses the virtual environment and uses it as the project interpreter.

If you need to configure a different virtualenv, open Preferences on a Mac, or use Ctrl+Alt+S to open Settings on a Windows or Linux system, and go to Project: ProjectName. Open the drop-down list and select Project Interpreter:

Select VirtualEnv from the drop-down list. If there are no items to select, click the Settings button to the right of the drop-down list and select Add… . The remaining steps are the same as for creating a new project.

☞ The Python learning package is pretty much natural

Search and navigate in PyCharm

In large projects, it’s hard to remember where everything is, so quick navigation and search is important. PyCharm provides these features. Next, we use the project opened in the previous section to practice the following shortcuts:

Search for code snippets in the current file: Use Cmd+F on a Mac, Ctrl+F on Windows or Linux.

Search for code snippets throughout the project: Use Cmd+Shift+F on Mac, Ctrl+Shift+F on Windows or Linux.

Search: Press Cmd+O on a Mac operating system, Ctrl+N on a Windows or Linux operating system.

Search for files: On a Mac, press Cmd+Shift+O; on a Windows or Linux, press Ctrl+Shift+N.

If you don’t know if you’re searching for files, classes, or code snippets, search all of them: Press Shift twice.

To navigate, use the following shortcut keys:

Go to the declaration of variables: On a Mac system use the Cmd key, on a Windows or Linux system use the Ctrl key, and then click the variable.

Find usage of classes, methods, or files: Use Alt+F7 keys.

To see Recent Changes: Use Shift+Alt+C or click View → Recent Changes from the main menu.

To View Recent Files: Use Cmd+E on a Mac, Ctrl+E on Windows or Linux, or click View → Recent Files from the main menu.

Press Cmd+[/ Cmd+] on a Mac operating system, Ctrl+Alt+Left/Ctrl+Alt+Right on a Windows or Linux operating system.

More details, see the official document: www.jetbrains.com/help/pychar…

Version control in PyCharm

Version control systems such as Git and Mercurial are among the most important tools in the modern software development world. Therefore, the IDE must support version control. PyCharm does this very well, integrating a number of popular version control systems such as Git (and Github (github.com/)), Mercuria… And Subversion.

Note: The version control system used in the following examples is Git.

Configuring the Version Control System (VCS)

For VCS integration, you need to click VCS → VCS Operations Popup from the top menu… Or Ctrl+V on a Mac or Alt+ ‘on Windows or Linux. Select Enable Version Control Integration… , you will see the following window:

Select Git from the drop-down list, click OK, and you have the VCS set up for your project. (Note that if you open an existing project that already has version control, PyCharm will find and use that version control system automatically.)

If you go to VCS Operations Popup… , you’ll find a different popover with options like git add, Git Stash, Git branch, git commit, git push, and so on:

If you can’t find the options you need, you can click VCS in the top menu and select Git, where you can create and view pull requests.

Commit and conflict handling

These are the two main features of VCS integration in PyCharm that I personally use a lot and love. If you have finished your work and want to submit it, go to VCS → VCS Operations Popup… To Commit… Or use Cmd+K on a Mac or Ctrl+K on A Windows or Linux operating system. You should see the following window:

In this window, you can:

Select the file to submit

Write the submission information

Perform checks prior to submission

See the changes

Click the arrow next to the Commit button in the lower right corner and select Commit and Push… To complete the commit and push in one go.

Doesn’t it feel magical and fast? Especially if you used to perform these tasks manually from the command line.

Merge conflicts occur in teamwork. When one person commits a change to a file you are working on, you both change the same row and the changes overlap, and VCS cannot decide whether to choose your changes or those of a teammate. Then you can use the following arrows and symbols to solve the problem:

As strange as it may seem, it’s hard to tell which changes to delete and which to keep. Fear not, PyCharm is coming! It can resolve conflicts in a better, more concise way. Go to VCS in the top menu, select Git, and then Resolve Conflicts… . Select the conflicting files and click Merge, the following window appears:

In the left column, you can view your changes. In the right column, you can view the changes made by teammates. The middle column displays the results. Conflicting lines of code are highlighted and you can see X and >>/<< next to them. Click the arrow to accept the change, and click the X to reject the change. Once all conflicts are resolved, click the Apply button:

In the figure above, for the first conflicting line, the author chooses to reject his own changes and accept his teammate’s. In the second conflict line, the author accepts his own changes and rejects his teammate’s.

A lot more can be done using the VCS integration in PyCharm. See www.jetbrains.com/help/pychar…

Use plug-ins and external tools in PyCharm

In PyCharm you can find almost everything you need for development. If not, there is a good chance that a plug-in exists that provides PyCharm with the functionality you need. For example, they can:

Added support for multiple languages and frameworks

Use shortcut Hints, file Watcher, etc to increase your productivity

Use code exercises to help you learn new programming languages

For example, the IdeaVim plug-in adds Vim emulation to PyCharm. If you like Vim, this plugin makes a good combination.

The Material Theme UI plugin changes the appearance of PyCharm to that of Material Design:

The vue.js plug-in enables PyCharm to support vue.js projects. The Markdown plug-in makes it possible to edit Markdown files within the IDE and preview the rendered HTML in real time.

Click Preferences → Plugins on Mac and Click Settings → Plugins on Windows or Linux to find and install all available Plugins under the Marketplace TAB:

If you still don’t find the plug-in you need, you can even develop one yourself.

If you can’t find the right plug-in and don’t want to develop it yourself because there is a package available on PyPI, you can add this package to PyCharm as an external tool. Take Flake8, the code analyzer, for example.

First, you install Flake8 ina virtual environment by typing PIP Install Flake8 in the selected Terminal app. Alternatively, you can use the Terminal integrated with PyCharm:

On a Mac, click Preferences → Tools. On a Windows or Linux OS, click Settings → Tools and select External Tools. Then click the + button at the bottom (1). In the window that pops up, enter the details and click OK in both Windows, as shown below:

In the figure above, Program (2) refers to Flake8, which you can find in the virtual environment folder (bin). Arguments (3) denotes the file you want to analyze with Flake8. Working directory indicates the project directory.

You can write out the absolute path of all items here, but that means you can’t use the external tool in other projects, only for one file in a project.

So you need Macros. It is a variable of the Namenamename format and varies according to context. For example, when you edit first.py, FileNameFileNameFileName is first.py, and when you edit second.py, FileNameFileNameFileName is second.py. To see a list of them, click Insert Macro… Button inserts one of them. Here you use Macros, their values will change depending on the project you are currently working on, and Flake8 will continue to do its job accurately.

To use it, you need to create the file example.py and write the following code in it:

The code above intentionally breaks some of Flake8’s rules. Right-click on the file background and select External Tools → Flake8. Flake8 analysis results will appear at the bottom of the window:

To make it even better, you can add shortcuts to it. Select Preferences on a Mac OS and Settings on a Windows or Linux OS. Then, click Keymap → External Tools → External Tools. Double-click Flake8 and select Add Keyboard Shortcut, the following window appears:

In the image above, the shortcut is Ctrl+Alt+A (used in this tutorial). You can add your favorite shortcut in the text box, and then click OK in both Windows. You can then use this shortcut to analyze the file you are currently working on with the help of Flake8.

PyCharm Professional function

PyCharm Professional is a paid version of PyCharm with more features and integration out of the box. This section provides an overview of the main features, as well as links to official documentation that details each feature. Keep in mind that none of the following features are available in the PyCharm Community version.

Django support

Django is the most popular and beloved Python Web framework, and PyCharm provides extensive support for Django. To ensure Django support, perform the following steps:

1. Open the Preferences in the Mac OS and Settings in the Windows or Linux OS.

2. Choose Languages and Frameworks.

3. Select Django.

4. Check the Enable Django Support check box.

5. Apply the changes.

Now that Django support is assured, your Django development journey in PyCharm will be a lot easier. Specifically, when you create a project, you get a dedicated Django project type. This means that when you select the type, you will have all the necessary files and Settings. This is equivalent to using Django-admin startProject mysite.

You can also run manage.py directly from within PyCharm. Currently supported Django templates include the following:

Syntax and errors are highlighted

Code completion

navigation

Block name completion

Customize labels and filter completion

Quick documentation of labels and filters

Template debug capability

In addition, you can perform code completion in other Django parts such as views, urls, and models, provide code insight support for Django ORM, and provide model dependency diagrams for Django models.

More details, see the official document: www.jetbrains.com/help/pychar…

Database support

Modern database development is a complex task that requires multiple support systems and workflows. This is why JetBrains developed a standalone IDE, DataGrip. DataGrip is a separate product from PyCharm, with different application scenarios and licenses.

Fortunately, PyCharm supports all the features in DataGrip through the Database Tools and SQL plug-in (which is enabled by default). With the help of this plug-in, you can query, create, and manage databases, whether they are local, on a server, or in the cloud. The plugin supports MySQL, PostgreSQL, Microsoft SQL Server, SQLite, MariaDB, Oracle, Apache Cassandra, and more.

More about the plug-in USES, please view the document: www.jetbrains.com/help/pychar…

Thread Concurrency Visualization

Django Channels, Asyncio, and recent frameworks such as Starlette (www.starlette.io/) show that asynchronous Python programming is becoming a trend. Asynchronous programming has many benefits, but it’s hard to write and debug. Thread Concurrency Visualization is the doctor in this case, helping you manage and optimize your multi-threaded application across the board.

More details, see the documentation: www.jetbrains.com/help/pychar…

Profiler

Speaking of optimization, profiling is another method of optimizing code. Profiling can help you see which parts of your code are taking up the most execution time. The profiler runs with the following priorities:

  1. vmprof

  2. yappi

  3. cProfile

If you don’t have VMProf or Yappi installed, run the standard cProfile. More details, see: www.jetbrains.com/help/pychar…

Scientific mode

Python is not only a general purpose and Web programming language, it is the best tool for data science and machine learning thanks to libraries and tools such as NumPy, SciPy, SciKit-Learn, Matplotlib, and Jupyter. With these powerful tools, you also need a powerful IDE to support all of the plotting, analysis, and other features that these libraries have.

More details about scientific mode, see www.jetbrains.com/help/pychar…

Remote development

A common reason for bugs in many applications is that the development and production environments are different. Although in most cases a perfect copy of the production environment is not realistic for development, striving for a perfect copy is a worthy goal.

With the help of PyCharm, you can debug your application using an interpreter on another machine, such as a Linux VM. This way, you can have the same interpreter as the production environment, avoiding many bugs caused by the development and production environment differences.

For details, see: www.jetbrains.com/help/pychar…

conclusion

PyCharm is one of the best Python development ides. It saves a lot of time by providing a number of advantages to help perform routine tasks. Now that you have completed this tutorial, do you know how to use PyCharm to increase productivity?


The most complete Python collection ever (long term update). The children next door are greedy to cry — click to receive