在 Windows 建立 Python 虛擬環境時,無法執行Activate.ps1的問題

 

在 Windows 建立 Python 虛擬環境時啟用 PowerShell 的 Execution Policy 教學

在 Windows 建立 Python 虛擬環境後,PowerShell 無法啟用 Activate.ps1 的解決方案

2025-08-13

在 Windows 系統中建立 Python 虛擬環境,例如透過

PowerShell
python -m venv venv

後,會生成一個 venv 資料夾。當你在 PowerShell 下嘗試啟用虛擬環境:

PowerShell
venv\Scripts\Activate.ps1

可能會出現以下警告:

PowerShell
cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.

原因說明

這是由於 PowerShell 的安全性機制 Execution Policy 所致。在預設情況下,Execution Policy 可能是最嚴格的 Restricted,不允許執行任何腳本。

可以用以下指令查詢目前狀態:

PowerShell
Get-ExecutionPolicy  # 知道目前的狀態

若結果為:

PowerShell
Restricted

表示當前環境禁止執行腳本(包含 Activate.ps1)。

解決方法

將 Execution Policy 從 Restricted 暫時調整為 Unrestricted,以便執行啟用腳本。以下提供兩種方式:

方法一:系統層級(需管理員權限,較不建議日常使用)

PowerShell(以系統管理員執行)
Set-ExecutionPolicy Unrestricted
使用後請記得在完成工作後,恢復原本的設定以維持系統安全。

方法二:僅限目前 PowerShell 視窗(推薦)

針對「目前進程(Process)」生效,關閉視窗後自動恢復:

PowerShell
Set-ExecutionPolicy Unrestricted -Scope Process

-Scope Process 是什麼?

Process 代表執行原則只在「目前的 PowerShell 進程」生效:

  • 關閉 PowerShell 後,設定會消失。
  • 不影響其他 PowerShell 視窗或系統全域設定。
  • 避免改動使用者或系統等級的安全設定,適合小型或臨時開發需求。

建議流程

  1. 開啟 PowerShell。
  2. 執行:
    Set-ExecutionPolicy Unrestricted -Scope Process
  3. 啟用虛擬環境:
    venv\Scripts\Activate.ps1
  4. 完成後關閉 PowerShell 視窗,即自動恢復預設安全設定。
參考資料:stackoverflow

留言

熱門文章

EUV?DUV?什麼是曝光機(光刻機),一看就懂超簡單

"曝光與蝕刻"半導體業的兩大技術,一看就懂超簡單

IC設計產業結構,一看就懂超簡單