LoginSignup
2
3

More than 3 years have passed since last update.

Ubuntuで新しいpythonの仮想環境を構築する方法

Last updated at Posted at 2020-05-13

目的

新しいpythonプロジェクトを始める際に、仮想環境を準備する手順を、備忘録として整理します。

実行環境

ホストOS: Windows 10 pro
仮想化ソフト: VirtualBox 6.0
ゲストOS: Linux Ubuntu 18.04
統合開発環境: VS Code 1.44.2

仮想環境の構築手順

venvを使うと、pipにより導入するパッケージをプロジェクト毎に独立させることができるので便利。
ただし、python 自体のバージョンは管理できないので、必要ならpyenv等の別のツールを用いる。(ここでは説明は割愛)

1.仮想環境を作成する

$ mkdir {new_project_name}
$ cd {new_project_name}
$ python3 -m venv {venv_name} //venv_nameは何でもよいが、使い勝手よいので原則venvとする

以下のようなエラー表示が出る場合、python3-venvパッケージがインストールされていないので、aptコマンドでインストールする。

The virtual environment was not created successfully because ensurepip is not
available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.
apt-get install python3-venv

$ apt install python3-venv

2. VSCodeのワークスペースを作成する

以下の手順で設定用ファイルを作成し、新規ワークスペースとして保存する。
1.以下のコマンドでVSCodeを開く

$ cd {Project_Directory}   // new_projectのディレクトリに移動
$ code .  // VSCodeを開く

2..gitignoreファイルを作成する

$ echo "/venv" > .gitignore

3.ワークスペースとして保存する
File >> Save Workspace As ... を選択すでと、保存ウィンドウが開くので、ワークスペース名を入力して保存する。

今後は以下のコマンドでワークスペースを開くことができる

$ cd { Project_Directory }    // new_projectのディレクトリに移動
$ code {new_workspace_name}.code-workspace

3.githubにリポジトリを作成する

githubのwebサイトから新しいリポジトリを作成する。
下記のサイトの、「4,github上で新規レポジトリを作成」を参考にしてください。

Githubに新規リポジトリを追加
https://qiita.com/sodaihirai/items/caf8d39d314fa53db4db

4.ローカル環境とgithubのリポジトリを連携する(ターミナルを利用する方法)

ターミナルから、以下のコマンドを実行する。

// 
cd { Project_Directory }    // new_projectのディレクトリに移動
git init
git add .
git commit -m "first commit"
git remote add origin https://github.com/{ User_Name }/{ Repository_Name }.git
git push -u origin master

githubのユーザー名とパスワードの入力が求められるので、入力しエンターを押す。
以上で完了です。

参考資料

venv: Python 仮想環境管理
https://qiita.com/fiftystorm36/items/b2fd47cf32c7694adc2e

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3