LoginSignup
44
42

More than 5 years have passed since last update.

PowerShellでvirtualenvを使うには

Posted at

virtualenvはPowerShellに対応していますが、PowerShellの設定によって使えない場合があります。その原因と対策についてまとめました。

virtualenvのactivateで「PSSecurityException」が発生する原因

PowerShellでvirtualenvのactivateを使うと、以下のエラーが発生する場合があります。

> virtualenv.exe venv
> .\venv\Scripts\activate
.\venv\Scripts\activate : このシステムではスクリプトの実行が無効になっているため、ファイル C:\Users\****\developme
nt\venv\Scripts\activate.ps1 を読み込むことができません。詳細については、「about_Execution_Policies」(http://go.microso
ft.com/fwlink/?LinkID=135170) を参照してください。
発生場所 行:1 文字:1
+ .\venv\Scripts\activate
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : セキュリティ エラー: (: ) []、PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

これは、PowerShellのスクリプト実行ポリシーが原因です。現在の実行ポリシーはGet-ExecutionPolicyコマンドで確認できます。

> Get-ExecutionPolicy
Restricted

Restrictedは「実行できるスクリプトはありません。Windows PowerShell は対話型モードでのみ使用できます。」という意味です。
実行ポリシーについての詳細はMicrosoftの公式ドキュメントを参照してください。

Restrictedのままだとactivateすることができません。対策として以下の方法があります。

対策1

管理者権限付きでPowerShellを立ち上げ、Set-ExecutionPolicyコマンドで実行ポリシーをRemoteSignedに変更します。RemoteSignedは「ダウンロードしたスクリプトは信頼できる発行元が署名した場合にのみ実行できます。」という意味です。

> Set-ExecutionPolicy RemoteSigned

「実行ポリシーを変更しますか?」というダイアログが出るので、「Y」を入力してEnterで先に進めてください。

なお、virtualenvの公式ドキュメントにはSet-ExecutionPolicy AllSignedでもいいと書いてあるのですが、1私の環境では以下のエラーが出てactivateできませんでした。

.\venv\Scripts\activate : ファイル C:\Users\****\development\venv\Scripts\activate.ps1 を読み込めません。ファイル
C:\Users\****\development\venv\Scripts\activate.ps1 はデジタル署名されていません。このスクリプトは現在のシステムで
は実行できません。スクリプトの実行および実行ポリシーの設定の詳細については、「about_Execution_Policies」(http://go.micr
osoft.com/fwlink/?LinkID=135170) を参照してください。
発生場所 行:1 文字:1
+ .\venv\Scripts\activate
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : セキュリティ エラー: (: ) []、PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

対策2

virtualenvだけのために設定を変えたくないという人は、対策1のコマンドに-Scope Processオプションを付けて、「今開いているPowerShellウィンドウのみ実行ポリシーを変更」にするのがオススメです。この場合はPowerShellに管理者権限は必要ないです。

> Set-ExecutionPolicy RemoteSigned -Scope Process

毎回ダイアログが出るのが面倒なら-forceオプションで省略できます。

対策後にvirtualenvのactivateを使ってみる

前述の対策実施後にactivateすればエラーは発生しなくなります。以下のように画面左にvirtualenvのディレクトリ名が表示されるはずです。

powershell.jpg

参考資料


  1. こう書いてあります→"In order to use the script, you can relax your system’s execution policy to AllSigned, meaning all scripts on the system must be digitally signed to be executed. Since the virtualenv activation script is signed by one of the authors (Jannis Leidel) this level of the execution policy suffices." 

44
42
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
44
42