banner
肥皂的小屋

肥皂的小屋

github
steam
bilibili
douban
tg_channel

Getting Started with Python: Environment Configuration - Anaconda, Pycharm, and the Formatting Tool Black

Anaconda#

What is Anaconda?#

An excellent integrated development environment for Python.

Why use it (Advantages)#

  • Solves the cumbersome environment and package issues: complex packages like lxml, PIL, etc.
  • Conveniently configure multiple environments: allows for easy switching between Python 2.x and 3.x series.
  • Comes with many useful data analysis tools: includes several open-source packages related to data science (such as Pandas, Scipy, etc.), covering various aspects like data visualization, machine learning, and deep learning.
  • Includes the Jupyter Notebook tool: development, debugging, and recording study notes can all be done on it.

Download, Install, and Configure#

  • Download: It is recommended to use the Tsinghua mirror for downloading: Click here to download, note that the sorting time is unordered; click on the Date column to change the sorting method:

image

You can also directly go to the Tsinghua University mirror site homepage for the common distribution iso and application tool installation package download interface:

image

Select application software -> conda, and download the latest version:

image

  • Installation: The default installation path is C:\Users\your_username\Anaconda3, it is recommended to change it to C:\Anaconda.

Make sure to check both options:

image

  • Configuration:

Changing Anaconda Source#

(Updated on 19-06-16) The Tsinghua and USTC mirrors in China stopped service in May 2019 due to copyright issues; please use a VPN.


(Updated on 19-06-28) Tsinghua University mirror has obtained authorization and resumed service on 2019-06-27:

After communication with Anaconda, Inc., we have obtained authorization for the mirror and will restore Anaconda-related services shortly. Thank you for your understanding and support.

According to our understanding, Anaconda, Inc. is willing to open the mirror permissions to educational and research institutions on the condition that traffic information is provided. However, individuals and groups wishing to set up Anaconda mirror sites (including becoming downstream of TUNA) should note that, according to the instructions on the Anaconda software source, Anaconda and Miniconda are trademarks of Anaconda, Inc., and any unauthorized public mirrors are not allowed. Please strictly follow the official regulations published by Anaconda, Inc. for mirroring; TUNA is not responsible for any legal consequences arising from this.

Thank you for your understanding and support!

Here is the tutorial for changing the Anaconda source:

After conda is installed, the default mirror is the official one. Since the official mirror is located abroad, access is too slow or not accessible. To speed up access, we choose the Tsinghua mirror. Run the following in the command line (to set Tsinghua's mirror):

conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/bioconda/
conda config --set show_channel_urls yes
  • Second, CondaHTTPError Issue (if it doesn't occur, you can skip this)

.condarc (the conda configuration file) starts with a dot, generally indicating the configuration file for the conda application, which is an optional runtime configuration file.

By default, it does not exist, but when the user runs the conda config command for the first time, this file will be created in the user's home directory:
windows: C:\\users\\username\\
linux: /home/username/

In the user's home directory, find the .condarc file and delete it.

To remove the Tsinghua source, just change add to remove.

Common Usage Methods:#

conda list: View installed packages
conda install Package-Names: Install a specific package, usage is the same as pip
conda --version: Check Anaconda version
conda info -e: View currently created environments
conda update --prefix C:\Anaconda anaconda (here is the installation directory): Update Anaconda
If you are too lazy to check the installation directory, just enter conda update, it will prompt you with the completed statement, just copy and execute it.
conda update --all: Update packages
Upgrade pip (after upgrading, you can use pip3): python -m pip install --upgrade pip

Adding Python 2.7 Environment to Py3.6 Version#

  • After installing Anaconda, there will be an application called Anaconda Navigator, which can be searched in the Windows menu:
    image

  • Open and run it, select the Enviroments option:
    image

  • You can see that there is only one ROOT environment by default; we can also check this by entering the command conda info -e in cmd.

  • Next, we will configure our Python 2 environment, click Create:
    image

  • Click Create, and after a while, the environment will be created:
    image

Generally speaking, the Python 3 series is the future's ruler, so we create Python 2.7 only for comparison of some examples.

Therefore, there is no need to "add system variables and modify exe file names to use Python2 and Python3 commands in the cmd window to enter the corresponding environment"; Anaconda provides us with a convenient solution:

We just need to enter activate Python2.7 (this name is the one we created above) in cmd to activate the Python 2.7 environment.

To deactivate the Python 2.7 environment and return to the Python 3.6 environment, just enter deactivate in cmd.

Here is an example:
image

Pycharm#

Tips: This article was created a while ago, and later soapffz realized that Pycharm is indeed very powerful, but the problems it brings are:

  • The software occupies a large amount of memory (my computer's default allocation of 725M will prompt that memory is low and suggest changing it to 1125M).
  • High CPU usage during initialization (CPU usage spikes sharply upon startup and then drops; even in power-saving mode, it can reach 50%).
  • Each startup loads the previous virtual environment, which takes about 1 minute.

So, it is not very friendly for beginners (ignore if you have a high-end machine); it is only suitable for professionals who frequently write large projects. Later, I will publish an article on VSC as the main tool for writing Python code.

VSC Portal:

Pycharm download address: Click here to download

Activation#

  • Add to hosts: 0.0.0.0 account.jetbrains.com
  • Location in Windows: C:\Windows\System32\drivers\etc, if permissions are insufficient, copy it out, add it, and then paste it back to overwrite.
  • linux, mac: /etc
  • Then open: http://idea.lanyus.com/, to get the activation code, which is attached, but the website is continuously updated.

Configuration#

  • Set theme font
    File -> Settings -> Editor -> Color Scheme -> Console Font, remember to back up before modifying.
    image

  • Set editor font
    File -> Settings -> Editor -> Font, similar to the above:
    image

  • Configure compiler and formatting plugins

Generally, if you open Pycharm after installing Anaconda, it will automatically recognize the compiler (provided Anaconda is added to the PATH environment variable), as shown below:

image

If the interpreter has not been configured, while editing code, you may see a prompt saying No Python interpreter configured for the project.

image

Clicking in will take you to this configuration area, then select the installed Python interpreter, and remember to check the two options below, which mean "inherit packages" and "common to all projects (no need to configure again)".

image

After a while, it will automatically create the virtual environment and read the installed packages, and the next time you reopen the project, it will automatically read them.

PS: Here you see an Existing environment, which literally means using an already existing environment. You might think, like I did, that after creating the environment for the first time, restarting and selecting the first created environment would work, but I tried, and it still went back to scanning environments and packages, and an extra (venv)(1) appeared in the interpreter, which seems incorrect. I also don't understand how this Existing environment is practically useful.

In settings -> Project Interpreter, the dropdown triangle in the upper right corner will show all Python versions configured with environment variables on your computer, allowing you to switch freely.

Formatting Tool Black (Python 3.6 and above)#

Introduction#

Introduction:

Code readability is one of the standards for judging code quality. One measure of code quality is the "WFT" law proposed by Martin, which is the frequency of "WTF" moments per minute. Have you ever felt the urge to say "WTF" when reading someone else's code or during a Code Review? To help developers unify code style, the Python community proposed the PEP8 coding style, which does not strictly require everyone to follow it. The Python official also released a tool to check whether the code style conforms to PEP8, named pep8, which was later renamed to pycodestyle.

Consider the following code:

import time, datetime

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None

    # in python next is a reversed word
    def reverse(self, head):
        prev = None
        while head:
            temp = head.next
            head.next = prev
            prev = head
            head = temp

        a = [
            [
                1,
                u'hello world',
                0
            ],
            [
                2,
                "hello python",
                0
            ],
        ]

This is a code snippet that does not conform to PEP8. Using pycodestyle can detect which places do not comply with PEP8 style.

$ pycodestyle link.py
link.py:1: [E401] multiple imports on one line
link.py:3: [E302] expected 2 blank lines, found 1

pycodestyle indicates that we have two places that do not comply with the standards: the first is multiple imports on a single line, and the second is that there should be two blank lines between classes and modules. This is just a simple code example; real business code may have hundreds of lines. If we want to modify according to PEP8 standards one by one, it would be very time-consuming, and if we constantly focus on whether every line of code fully adheres to PEP8 during development, it will affect development efficiency.

There is a tool called Black, which is known as an uncompromising code formatter. Why is it called uncompromising? Because it directly formats all non-compliant code styles without requiring you to confirm, making decisions for you. It is also one of the favorite tools of the requests author.

Using it is very simple; after successful installation, use it like other system commands, just specify the file or directory to be formatted after the black command: black link.py.

image

This is a small but beautiful tool; it does not format strictly according to PEP8 standards. For example, the default number of characters per line is 88, but you can customize the length with the -l parameter. It will place code that can fit in one line on one line, such as a list with multiple elements.

# in:

l = [1,
     2,
     3,
]

# out:

l = [1, 2, 3]

The latter puts multiple elements on one line, which is clearly more readable and makes the code more compact (if your salary is based on the number of lines of code, it is not recommended to do this). Black is a strict subset of PEP8. My best practice is to use the built-in formatting tool of PyCharm in conjunction with Black, as Black also supports integration into Pycharm.

How to Integrate into Pycharm#

  1. Install black (if conda doesn't work, use pip): pip install black

  2. Find the installation path of black: where black (windows) / which black (linux/mac):

    image

  3. Add an external tool, open Settings -> Tools -> External Tools, and add a new external tool. Fill in the installation path of black for Program and $FilePath$ for Arguments.

    image

  4. Select Tools -> External Tools -> Black to format the currently opened file and code. Of course, you can also assign a shortcut key to make it more convenient to operate.

    image

For more information, you can refer to the documentation: GitHub Portal

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.