네이티브 리눅스 앱을 Windows 11 and later OS build 에서 실행할 수 있는 Windows Subsystem for Linux 이다.
WSL 1 vs. WSL 2
WSL2 is the second generation of WSL that offers the following benefits:
Linux applications can run as is in WSL2. WSL 2 is characteristically a VM with a Linux WSL Kernel in it that provides full compatibility with mainstream Linux kernel allowing support for native Linux applications including popular Linux distros.
Faster file system support and that’s more performant.
WSL 2 is tightly integrated with the Microsoft Windows operating system, which allows it to run Linux applications alongside and even interop with other Windows desktop and modern store apps.
2. NVIDIA GPU Accelerated Computing on WSL 2
WSL 2에서 마이크로소프트는 NVIDIA CUDA 및 기타 컴퓨팅 프레임워크와 기술과 함께 데이터 과학, 머신러닝 및 추론 솔루션을 위한 GPU 가속 컴퓨팅을 가능하게 하는 GPU 반가상화 기술을 도입했다. WSL 유사 환경 또는 WSL 2에서 CPU 개입을 줄이면서 GPU에서 더 많은 병렬 작업을 파이프라인으로 수행할 수 있으므로 거의 네이티브에 가까운 성능을 제공한다. NVIDIA 드라이버 지원은 CUDA 및 관련 컴퓨팅 소프트웨어 스택에서 멈추지 않습니다. 다이렉트 ML 지원과 함께 DX12 API를 지원하여 WSL 2에서 그래픽을 활성화하는 DirectX 지원이 있습니다.
Illustration of the possibilities with NVIDIA CUDA software stack on WSL 2
3. WSL2 시작
WSL2 요구사항
Geforce, Quadro 제품 계열에서 Pascal 또는 최신 GPU 구조를 WDDM모드로 SKU를 사용할 수 있다.
최신 WSL 커널 로 5.10.16.3 이상을 권장한다. (최소 4.19.121+ 이상)
Windows 11 에서는 윈도우 인사이더 프로그램 가입이 필요 없다.
Windows 10 에서는 윈도우 인사이더 프리뷰 프로그램이 필요하다.
Step 1: Install NVIDIA Driver for GPU Support
윈도우 11 그래픽 드라이버로 NVIDIA GeForce Game Ready or NVIDIA RTX Quadro 를 설치한다.
(tf25gpu_p39)~$ nvidia-smi Sun Dec 5 02:29:22 2021 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 510.00 Driver Version: 510.06 CUDA Version: 11.6 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 NVIDIA GeForce ... On | 00000000:09:00.0 On | N/A | | 0% 43C P8 20W / 320W | 1179MiB / 11264MiB | N/A Default | | | | N/A | +-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=============================================================================| | No running processes found | +-----------------------------------------------------------------------------+
Initializing data... ...allocating CPU memory for options. ...allocating GPU memory for options. ...generating input data in CPU mem. ...copying input data to GPU mem. Data init done.
Executing Black-Scholes GPU kernel (512 iterations)... Options count : 8000000 BlackScholesGPU() time : 0.234201 msec Effective memory bandwidth: 341.586668 GB/s Gigaoptions per second : 34.158667
weather.main Group of weather parameters (Rain, Snow, Extreme etc.)
weather.description Weather condition within the group
weather.icon Weather icon id
base Internal parameter main main.temp Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. main.pressure Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa main.humidity Humidity, % main.temp_min Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. main.temp_max Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit. main.sea_level Atmospheric pressure on the sea level, hPa main.grnd_level Atmospheric pressure on the ground level, hPa wind wind.speed Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour. wind.deg Wind direction, degrees (meteorological) clouds clouds.all Cloudiness, % rain rain.3h Rain volume for the last 3 hours snow snow.3h Snow volume for the last 3 hours dt Time of data calculation, unix, UTC sys sys.type Internal parameter sys.id Internal parameter sys.message Internal parameter sys.country Country code (GB, JP etc.) sys.sunrise Sunrise time, unix, UTC sys.sunset Sunset time, unix, UTC id City ID name City name cod Internal parameter
An API that provides network-based access to resources via a uniform interface of self-descriptive messages containing hypertext to indicate potential state transitions might be part of an overall system that is a RESTful application – Roy T. Fielding
구현이 쉽지는 않다.
원격 API가 REST API여야 하나?
시스템 전체를 통제할 수 있다고 생각하거나, 진화에 관심이 없다면, REST에 대해 따지느라 시간을 낭비하지 마라
REST emphasizes evolvability to sustain an uncontrollable system. If you think you have control over the system or aren’t interested in evolvability, don’t waste your time arguing about REST. – Roy T. Fielding
현재는
(1) REST API를 구현하고 REST API라고 부른다. (2) REST API 구현을 포기하고 HTTP API라고 부른다. (3) REST API가 아니지만 REST API라고 부른다. (현재 상태)
그러므로 제약 조건을 따르던지 다른 단어를 써라!!!
I am getting frustrated by the number of people calling any HTTP-based interface a REST API. … Please try to adhere to them or choose some other buzzword for your API. – Roy T. Fielding
raspbian-wheezy에는 Python 2.7과 Python 3.2가 설치되어 있습니다.
Python tools
파이썬으로 개발하며 필요한 도구를 설치해서 사용하면 좋습니다. 파이썬 패키지 관리 도고, 가상 개발 환경 등의 설치를 통해서
APT로 설치
라즈비안에서 사용하는 파이썬 패키지들은 apt를 이용해서 라즈비안 저장소의 다양한 패키지를 사용할 수 있습니다. apt로 파이썬 패키지를 설치해 사용할 수 있는데 Python 2.x와 Python 3.x의 호환을 위해서 Python 2.x는 ‘python-‘ 접두어를 사용하고 Python 3.x 패키지들은 ‘python3-‘ 를 사용합니다. 예를 들어 picamera 패키지는 python-picamera와 Python 3.x 버전을 위해서 python3-picamera가 있습니다.
사전 준비
기본 개발자 모듈이 설치 안되어 있다면 설치한다.
1
$ sudo apt install build-essential
Python 개발을 위해서는 리눅스에 파이썬 헤더가 필요하다. 그래서 python-dev 패키지를 설치해 준다. Jessie에서 Python3.4 헤더는 설치가 되어 있다.
1 2
$ sudo apt-get install python3-dev python3-dev is already the newest version.
python2 개발환경을 위해서 헤더를 설치하려면
1 2 3 4
$ sudo apt install python-dev
The following extra packages will be installed: libexpat1-dev libssl-dev libssl-doc python2.7-dev
pip
전통적인 파이썬 패키지 도구인 PIP(Python Package Index, PyPI)를 이용하면 폭넓게 범위를 넓힐 수 있습니다.
Raspbian Jessie : 기본으로 제공 apt를 이용해 저장소에 있는 외부 패키지를 설치해 사용할 수 있습니다. 그렇지만 개발에 필요한 모든 패키지가 라즈비안 저장소에 있지 않거나 오래된 버전일 수 있습니다.
Python2.x용 pip는 python-pip를 설치하고 Python3.x pip는 python-pip3 를 설치합니다.
Raspbian에서 사용자 계정에서 pip 설치하면 퍼미션 에러가 발생한다. OSError: [Errno 13] Permission denied: ‘/usr/local/lib/python2.7/dist-packages/pip-7.1.2.dist-info’ sudo 명령으로 설치해야 한다.
슈퍼사용자로 pip 설치시 사용자 계정에서 사용하기 불편한 점이 많다. 그래서 가상 개발환경을 구성해 사용자 계정에서 제약없이 사용하도록 한다.
pip 사용
pyhthon2, python3 버전이 설치되어서 pip도 역시 해당 버전이 별도로 설치되어 있습니다. 다음 버전 저보를 출력하면 어떤 버전인지 확인이 가능합니다.
1 2 3 4
$ pip3 --version pip 8.1.2 from /usr/local/lib/python3.5/dist-packages (python 3.5) $ pip2 --version pip 8.1.2 from /usr/local/lib/python2.7/dist-packages (python 2.7)
특정 파이썬 버전의 패키지 모듈을 설치한다면 해당 pip 버전을 호촐하는게 정확합니다.
upgrade pip
pip 는 다음 같이 업그레이드 해야 합니다.
1
$pip install -U pip
On Windows [5]:
1
$python -m pip install -U pip
Python 버전 관리자
다양한 파이썬 버전을 위해 환경 구성을 해주는 유틸리티.
pyenv : “Simple Python Version Management”, 로컬에 다양한 파이썬 버전을 설치하고 사용할 수 있도록 한다. pyenv를 사용함으로써 파이썬 버전에 대한 의존성을 해결할 수 있다.
virtualenv : “Virtual Python Environment builder”, 로컬에 다양한 파이썬 환경을 구축하고 사용할 수 있도록 한다. 일반적으로 Python Packages라고 부르는 ( pip install을 통해서 설치하는 ) 패키지들에 대한 의존성을 해결할 수 있다.
virtualenv와 virtualenvwrapper를 사용할 것이다.
autoenv : 만약 pyenv와 virtualenv를 통해서 의존성을 해결한다고 하더라도 작업할때마다 설정해주는 것은 귀찮은 작업이다. 특정 프로젝트 폴더로 들어가면 자동으로 개발 환경을 설정해주는 autoenv라는 스크립트를 활용하자.
여기서는 virtualenv를 설치하고 virtualenvwrapper를 사용해서 모듈을 설치하고 관리한다. 그러기 위해서 먼저 시스템의 기본 /usr/bin/python 버전을 확인하고 해당 버전의 pip 모듈을 사용해서 virtualenv 와 virtualenvwrapper 를 설치한다.
virtualenv
virtualenv는 가상의 파이썬 작업환경을 만들어 준다. 작업환경을 따로따로 만들어주면 해당 환경 내의 파이썬으로 무슨 짓을 해도 시스템 파이썬이나 다른 가상의 작업환경에게 영향을 주지 않는다. pip로 설치할 수 있습니다.
pip는 시스템의 site-packages 폴더에, /usr/lib/python2.7/site-packages에 모듈을 설치한다. virtualenv를 이용하면 분리할 수 있다.
단, 현재 python2.7과 python3.4가 공존하는 상태에서 virtualenv는 python2.x를 기반으로 만들어 져서 /usr/bin/python을 찾는데 그래서 다음 같이 pip2 버전으로 virtualenv를 설치해 준다.
1
$ pip install virtualenv
virtualenv는 python 버전에 관계 없이 하나만을 설치해 두면 된다.
virtualenvwrapper
virtualenvwrapper는 virtualenv 통합 환경을 좀 더 쉽게 접근할 수 있도록 도와줍니다. ‘virtualenv’ 가 설치된 글로벌 사이트 패키지 위치에 설치되야 합니다. 아마 관리자 권한이 필요할 것입니다.
그리고 쉘 환경을 로딩하기 위해서 다시 로그인 하거나 다음 같이 source 명령을 이용해도 좋습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
$ source .profile ebian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Fri Oct 23 18:17:41 2015 from 192.168.219.103 virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/premkproject virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/postmkproject virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/initialize virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/premkvirtualenv virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/postmkvirtualenv virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/prermvirtualenv virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/postrmvirtualenv virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/predeactivate virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/postdeactivate virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/preactivate virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/postactivate virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/get_env_details
다음 에러가 발생하면 쉘에 VIRTUALENVWRAPPER_PYTHON 를 추가해 준다.
/usr/bin/python: No module named virtualenvwrapper virtualenvwrapper.sh: There was a problem running the initialization hooks.
If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is
Quick-Start
다음 같이 virtualenvwrapper 를 사용할 수 있습니다.
workon 명령으로 실행 가상 환경 목록 혹은 변경한다.
1
$workon
실행 가상 환경 ‘raspberrypi2’ 생성
1 2 3 4 5 6 7 8 9 10 11
$ mkvirtualenv -p python2 raspberrypi2 New python executable in raspberrypi2/bin/python2.7 Also creating executable in raspberrypi2/bin/python Installing setuptools, pip, wheel...done. virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/raspberrypi2/bin/predeactivate virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/raspberrypi2/bin/postdeactivate virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/raspberrypi2/bin/preactivate virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/raspberrypi2/bin/postactivate virtualenvwrapper.user_scripts creating /home/pi/.virtualenvs/raspberrypi2/bin/get_env_details
(raspberrypi2)pi@raspberrypi ~ $ # 실행 가상 환경 쉘
프로젝트 환경을 빠져 나오려면 ‘deactivate’를 실행한다.
1
(raspberrypi2):~$ deactivate
rpi.gpio
1
(raspberrypi2)$pip install rpi.gpio
이제 이 디렉토리 밑에서 코드 작업을 하고 사용하면 됩니다.
다른 Python 버전 환경 만들기
1 2 3 4 5 6
$ mkvirtualenv -p python3 rpi_py3 Running virtualenv with interpreter /usr/bin/python3 New python executable in rpi_py3/bin/python3 Also creating executable in rpi_py3/bin/python Installing setuptools, pip...done. ...
virtualenv 사용
위의 설명과 같이 고립된 작업환경을 만들려면 디렉토리 구조를 잘 구성해야 합니다. 다음 같이 라즈베리파이 프로그램을 작업할 ‘Blinke’ 디렉토리를 만듭니다. Blinken은 LED를 깜박이는 작업을 수행할 것입니다.
1 2 3 4 5 6 7
$mkdir blinken $cd blinken $virtualenv env New python executable in env/bin/python Installing setuptools, pip...done. $. env/bin/activate (env)$
마지막 명령으로 가상환경을 활성화시키면 프롬프트 앞에 (env)가 표시됩니다. 가상환경을 바탕으로 환경 설정이 동작한다는 것을 의미합니다. 이제 필요한 파이썬 패키지 및 프로그램을 설치하고 개발을 할 수 있습니다.
$ sudo pip3 install virtualenvwrapper Collecting virtualenvwrapper Using cached virtualenvwrapper-4.7.1-py2.py3-none-any.whl
mkvirtualenv에서 python3의 환경을 하나 설치한.다.
1 2 3 4 5 6
$ mkvirtualenv -p python3 rpi_py3 Running virtualenv with interpreter /usr/bin/python3 New python executable in rpi_py3/bin/python3 Also creating executable in rpi_py3/bin/python Installing setuptools, pip...done. ...
가상환경 복사하기
cpvirtualenv oldenv newenv rmvirtualenv oldenv
pyvenv
3.3에서부터 pyvenv에 기본으로 설치되어 있다. 다만 3.3에서는 pip를 가상 환경을 만들 때마다 설치해주어야 한다. 3.4에서는 pip까지 기본으로 설치되어 있다.
1 2 3 4 5
$ mkdir django_tests $ cd django_tests $ pyvenv-3.4 env $ source env/bin/activate # env의 파이썬 활성화 (env)$ deactivate # 시스템 파이썬으로 복귀