Create a C ++ and Python execution environment with WSL2 + Docker + VSCode

I'm using C ++ and Python in the competition pro, and I wanted an execution environment on Windows, so I made it. Since it is not for development, it is the minimum required setting.

2020/1/11: Added "C ++ Standard Settings" to allow you to use C ++ 17 grammar on VSCode

Target

--For those who want to create a simple execution environment for C ++ and Python --Windows users --Docker installed --For those using VSCode

Usage environment / tools

Sample repository of execution environment created in this article: https://github.com/e5pe0n/algo-training-sample

Create a repository on GitHub

Create a repository on GitHub to make it easier to manage your code. Enter an appropriate Repository Name, check Add a README file, and click Create Repository. .gitignore will be created later, so don't check it here.

Create a New Repository - Google Chrome 1_3_2021 11_50_21 AM (2)_LI.jpg

Creating a Dev Container

Clone the repository you just created to the Docker container that will be the execution environment.

Put Remote Development in VSCode

First, open VSCode and install the extension Remote Development (ms-vscode-remote.vscode-remote-extensionpack) so that you can connect to the container from VSCode.

Extension_ Remote Development - Visual Studio Code 1_3_2021 12_01_58 PM.png

Associate VSCode with GitHub

When the installation is complete, a green button that allows you to use the Remote Development function will be displayed at the bottom left of the editor. Click it. Click Remote-Containers: Clone Repository in Container Volume from the menu that appears.

Extension_ Remote Development - Visual Studio Code 1_3_2021 12_03_34 PM_LI.jpg

Enter the URL of the repository and press enter.

Extension_ Remote Development - Visual Studio Code 1_3_2021 12_03_57 PM (2).png

For the first time, you'll be prompted to sign in to your GitHub account with VSCode, or you'll be asked to jump to your browser to allow VSCode to access GitHub, click Yes or Continue, respectively.

Extension_ Remote Development - Visual Studio Code 1_3_2021 12_04_05 PM.png GitHub for VS Code - Google Chrome 1_3_2021 12_04_28 PM (3).png Visual Studio Code 1_3_2021 12_05_25 PM.png

Branch to clone

When VSCode and GitHub are linked, you will be asked for the branch to clone, so select main. Visual Studio Code 1_3_2021 12_06_16 PM (2).png

Volume type

Since it will not be used with other repositories, select Create a unique volume this time. Welcome - Visual Studio Code 1_3_2021 12_07_36 PM (2).png

Container type

Let's set the container type to Ubuntu. Then you will be asked for the version, but set it to focal.

Welcome - Visual Studio Code 1_3_2021 12_08_02 PM (2).png

With this, I was able to create a container linked to the repository for the time being. From here, we will arrange the container settings so that C ++ and Python can be executed.

Container settings

When the container is created for the first time, it will have the following directory structure. From here, you can edit the configuration file or add a new configuration file.

/workspaces/<repo-name>
├── .devcontainer
│   ├── devcontainer.json
│   └── Dockerfile
├── .git
└── README.md

The final directory structure looks like this.

/workspaces/<repo-name>
├── .clang-format
├── .devcontainer
│   ├── devcontainer.json
│   └── Dockerfile
├── .git
├── .gitignore
├── README.md
└── requirements.txt

Create .gitignore

Execute touch .gitignore directly under the repository directory to create an empty file. In gitignore.io, enter vscode,C ++, Python and click Create. Copy all the displayed contents to the .gitignore created earlier, and you're done. Edit it if necessary.

Editing Dockerfile

In the following part of Dockerfile # [Optional] Uncomment this ..., add the command to be executed when the container is created. The build-essential installed with apt-get contains the C ++ compiler g ++, and clang-format is for formatting C ++ files. Also, Python 3.8.2 is included by default, but since the Python package installer pip is not included, python3-pip is installed.

# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.154.0/containers/ubuntu/.devcontainer/base.Dockerfile

# [Choice] Ubuntu version: bionic, focal
ARG VARIANT="focal"
FROM mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT}

# [Optional] Uncomment this section to install additional OS packages.
RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
    && apt-get -y install --no-install-recommends \
    build-essential \
    clang-format \
    python3-pip

Creating a .clang-format

Prepare .clang-format as a C ++ file format setting file. By turning on VSCode autoformat and setting the C ++ formatter to Clang-Format, you can automatically format the code as set in .clang-format. There are so many items that can be set (https://clang.llvm.org/docs/ClangFormatStyleOptions.html), so you can set it as you like. To be honest, I don't really understand it, so I set only the ones that interest me.

.clang-format


ColumnLimit: 110
AllowShortBlocksOnASingleLine: true
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: true
BinPackArguments: false
BinPackParameters: false
BreakBeforeBinaryOperators: NonAssignment
ConstructorInitializerAllOnOneLineOrOnePerLine: true
IndentWidth: 2

Creating requirements.txt

requirements.txt is a file used for Python package management. You can list the packages here and run pip3 install -r requirements.txt to install the required packages with one command. The following packages will be introduced.

package Explanation
numpy For matrix calculation and numerical calculation
flake8 Linter
autopep8 Formatter

After installing these with pip3 install, write a list of installed packages to requirements.txt with pip3 freeze.

$ pwd
/workspaces/<repo-name>
$ pip3 install numpy flake8 autopep8
$ pip3 freeze > requirements.txt

I think that requirements.txt is as follows, including the dependent packages.

requirements.txt


autopep8==1.5.4
flake8==3.8.4
mccabe==0.6.1
numpy==1.19.4
pycodestyle==2.6.0
pyflakes==2.2.0
toml==0.10.2

Editing devcontainer.json

This is the container configuration file. By writing VSCode settings and commands after the container is created in this, the settings will be automatically reflected when the container is created.

option Explanation
settings Container-specific VSCode settings
extensions VS Code extensions for use in containers
postCreatedCommand The command you want to execute after the container is created

settings

This is the part to write the VSCode settings.

option Explanation
editor.formatOnSave trueAutomatically format when saving a file with
python.languageServer Python IntelliCode server
python.pythonPath Python interpreter path to use
python.linting.flake8Args argument of flake8
python.formatting.provider Select Python formatter
[cpp]->editor.tabSize C++Number of indented characters in the file
[cpp]->editor.defaultFormatter C++Select a formatter

extensions

Here is a list of VS Code extensions you want to install. I am writing the following for the time being.

Extensions ID Explanation
Visual Studio IntelliCode visualstudioexptteam.vscodeintellicode AI Assistant will offer code completion
C/C++ ms-vscode.cpptools C++for
Clang-Format xaver.clang-format C++File formatter
Git Extension Pack donjayamanne.git-extension-pack For Git
Python ms-python.python For python
Pylance ms-python.vscode-pylance For python
Bracket Pair Colorizer 2 coenraads.bracket-pair-colorizer-2 Colors the corresponding parentheses
Trailing Spaces shardulm94.trailing-spaces Highlight / remove extra space
Vim vscodevim.vim Vim emulator for VSCode

postCreateCommand

This is where I write the command to be executed after the container is created. By writing pip3 install -r requirements.txt here, the package of requirements.txt written earlier will be installed automatically.

remoteUser

If you want to connect to the container as root, comment it out as follows. I use it as a basic root because it is troublesome around permissions.

// "remoteUser": "vscode"

With these settings, devcontainer.json looks like this.

// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.154.0/containers/ubuntu
{
	"name": "Ubuntu",
	"build": {
		"dockerfile": "Dockerfile",
		// Update 'VARIANT' to pick an Ubuntu version: focal, bionic
		"args": {
			"VARIANT": "focal"
		}
	},
	// Set *default* container specific settings.json values on container create.
	"settings": {
		"terminal.integrated.shell.linux": "/bin/bash",
		"editor.formatOnSave": true,
		"python.languageServer": "Pylance",
		"python.pythonPath": "/usr/bin/python3",
		"python.linting.flake8Args": [
			"--max-line-length", //Set the number of characters per line to 110
			"110"
		],
		"python.formatting.provider": "autopep8",
		"python.formatting.autopep8Args": [
			"--max-line-length", //Set the number of characters per line to 110
			"110"
		],
		"[cpp]": {
			"editor.tabSize": 2,
			"editor.defaultFormatter": "xaver.clang-format" //Extension Clang-Select Format
		},
	},
	// Add the IDs of extensions you want installed when the container is created.
	"extensions": [
		"visualstudioexptteam.vscodeintellicode",
		"ms-vscode.cpptools",
		"xaver.clang-format",
		"donjayamanne.git-extension-pack",
		"ms-python.python",
		"ms-python.vscode-pylance",
		"coenraads.bracket-pair-colorizer-2",
		"shardulm94.trailing-spaces",
		"vscodevim.vim"
	],
	// Use 'forwardPorts' to make a list of ports inside the container available locally.
	// "forwardPorts": [],

	// Use 'postCreateCommand' to run commands after the container is created.
	"postCreateCommand": "pip3 install -r requirements.txt",

	// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
	// "remoteUser": "vscode"
}

This completes the container settings.

Rebuilding the container

As a finishing touch, rebuild the container based on the settings. Click the green Dev Container: Ubuntu at the bottom left and select Remote-Containers: Rebuild Container.

devcontainer.json - algo-training-sample [Dev Container_ Ubuntu] - Visual Studio Code 1_3_2021 5_20_06 PM_LI.jpg

Now you have a C ++ and Python execution environment. After the rebuild is complete, for example, the following hello.cpp and hello.py can be executed in the container.

hello.cpp


#include <bits/stdc++.h>
using namespace std;

int main() {
  cout << "I'm C++!" << endl;
}
# g++ -o hello hello.cpp
# ./hello 
I'm C++!

hello.py


print("I'm Python!!")
# python3 hello.py
I'm Python!!

After that, if you push this to a remote repository, you can create the same environment immediately.

C ++ Standard settings

If the extension C/C ++ writes the grammar of C ++ 17, an error message will be displayed if it is left in, so set C ++ Standard. Open the command palette with Ctrl + Shift + P and selectC/C ++: Edit Configurations (JSON).

hello.cpp - algo-training-sample [Dev Container_ Ubuntu] - Visual Studio Code 1_10_2021 11_45_26 PM_LI.jpg

Then, the directory .vscode will be created directly under/workspaces, and c_cpp_properties.json will be created in it. Set cppStandard in this to"gnu ++ 17".

c_cpp_properties.json


{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++17",
            "intelliSenseMode": "gcc-x64"
        }
    ],
    "version": 4
}

For example, the following code with structured binding will no longer display the error message.

hello.cpp - algo-training-sample [Dev Container_ Ubuntu] - Visual Studio Code 1_11_2021 12_01_38 AM.png

bonus

When I create a new directory, I want to separate the C ++ and Python directories, so I put the following directories in the repository as templates.

template
├── cpp
│   ├── build         // C++Executable file storage
│   │   └── .gitkeep
│   ├── .gitkeep
│   └── run.sh        // C++File execution script
└── python
    └── .gitkeep

run.sh


f=`echo $1 | sed -e 's/\(.*\).cpp/\1/'`
current_dir=$(eval pwd)
g++ -std=c++17 -g -o ${current_dir}/build/${f}.out $1
eval ${current_dir}/build/${f}.out

run.sh is a script that compiles and executes C ++ files, and is used like sh run.sh A.cpp. I would love to know if there is a better way to use it in the competition pro!

Recommended Posts

Create a C ++ and Python execution environment with WSL2 + Docker + VSCode
Create a Python execution environment for Windows with VScode + Remote WSL
Create a simple Python development environment with VSCode & Docker Desktop
Create a simple Python development environment with VS Code and Docker
Build PyPy and Python execution environment with Docker
[Python] Create a virtual environment with Anaconda
Try to create a python environment with Visual Studio Code & WSL
Create a Python environment
Prepare the execution environment of Python3 with Docker
Building a python environment with virtualenv and direnv
Create a virtual environment with conda in Python
[Python] Build a Django development environment with Docker
Create a python3 build environment with Sublime Text3
Create a Python execution environment on IBM i
[Docker] Create a jupyterLab (python) environment in 3 minutes!
Build a python execution environment with VS Code
Create a Python3 environment with pyenv on Mac and display a NetworkX graph
Building a Docker working environment for R and Python
Build a python virtual environment with virtualenv and virtualenvwrapper
Build a Python + bottle + MySQL environment with Docker on RaspberryPi3! [Trial and error]
Create a python development environment with vagrant + ansible + fabric
Prepare python3 environment with Docker
Build a python virtual environment with virtualenv and virtualenvwrapper
Create a Layer for AWS Lambda Python with Docker
Create a directory with python
Create a decent shell and python environment on Windows
Build a local development environment with WSL + Docker Desktop for Windows + docker-lambda + Python
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
[Linux] Create a self-signed certificate with Docker and apache
Until you create a machine learning environment with Python on Windows 7 and run it
Let's create a PRML diagram with Python, Numpy and matplotlib.
Create a Todo app with Django ① Build an environment with Docker
Build a Python environment with WSL + Pyenv + Jupyter + VS Code
Solve ABC163 A ~ C with Python
Create Awaitable with Python / C API
Create a Python environment on Mac (2017/4)
Build Mysql + Python environment with docker
Building a virtual environment with Python 3
Solve ABC168 A ~ C with Python
Build PyPy execution environment with Docker
Create a python environment on centos
Solve ABC167 A ~ C with Python
Solve ABC158 A ~ C with Python
Building a Docker working environment for R and Python 2: Japanese support
Build a 64-bit Python 2.7 environment with TDM-GCC and MinGW-w64 on Windows 7
Build a Python environment on your Mac with Anaconda and PyCharm
Create a striped illusion with gamma correction for Python3 and openCV3
Create a development environment for Go + MySQL + nginx with Docker (docker-compose)
Build a Python execution environment using GPU with GCP Compute engine
[Mac] Create a Python3 execution environment from the fully initialized state
How to build Python and Jupyter execution environment with VS Code
Create a USB boot Ubuntu with a Python environment for data analysis
[DynamoDB] [Docker] Build a development environment for DynamoDB and Django with docker-compose
LaTeX and R (a little Python) environment construction with SublimeText3 (Windows)
[Pyenv] Building a python environment with ubuntu 16.04
Create a Python function decorator with Class
Building a Python3 environment with Amazon Linux2
Build Jupyter Lab (Python) environment with Docker
Build a blockchain with Python ① Create a class
Create a dummy image with Python + PIL.
Create a python environment on your Mac