此篇文章將學習到如何在 Windows 中製作一個 Python 可攜式版本。 當我們想要分享 Python 程式給朋友使用,或者需要在其他電腦上開發 Python 程式時,可能會碰到電腦沒有安裝 Python 環境的情況,這樣就無法運作我們的程式。在這種情況下,Python 可攜式版本是一個很好的解決方案。 --- [TOC] --- ## 一、Python 可攜式版本簡介: Python 可攜式版本是一個能夠隨身攜帶並在任何地方運作的 Python 環境。這意味著可以將其儲存在隨身碟或者雲端空間中,並隨時隨地運行 Python 程式,而無需依賴特定的電腦或環境。這使得在不同的電腦上開發和執行 Python 程式變得更加方便和靈活。 ## 二、Python 可攜式版本製作: 1. 前往 Python 官網中的 Windows 版本下載頁面。 網址:https://www.python.org/downloads/windows/  2. 選擇 Windows embeddable package 下載,這邊使用 Python 3.11.9 版本作為示範。  3. 解壓縮剛才下載回來的 Zip 檔案。  4. 執行資料夾中的 python.exe,如果能正常開啟以及運行 Python 程式,恭喜完成 Python 可攜式版本的製作。   ## 三、Python 可攜式版本 pip 安裝: 1. 前往 `get-pip.py` 頁面,然後右鍵呼叫功能選單,選擇另存新檔。 連結:https://bootstrap.pypa.io/get-pip.py  2. 將剛剛下載的 `get-pip.py` 移動到 Python 可攜式版本資料夾中。  3. 在檔案總管上方路徑欄中輸入 cmd 按下 Enter,開啟當前資料夾的 cmd 視窗。   4. 輸入以下指令來安裝 pip 工具,`.\python.exe` 意思是使用當前路徑的 Python 來執行程式。 ```powershell .\python.exe get-pip.py ```  5. 尋找當前資料夾中副檔名為 `._pth` 的檔案開啟,檔案名稱是以 Python 大版本命名。  6. 將第五行的 `#import site` 刪除 `#` 變成 `import site`,然後儲存檔案。  7. 輸入以下指令後,如果有出現以下圖片的內容,代表成功安裝 pip 工具。 ```powershell .\python.exe -m pip list ```  ## 補充、Batch file 製作: 在 cmd 中打指令執行 Python 程式,對於開發人員來說小菜一碟,但對一般電腦使用者來說卻是一大難事。當我們想要分享 Python 程式給朋友時,即使已經解決執行環境的問題,但仍然可能會遇到朋友不會打指令的問題。為了讓朋友能夠輕鬆執行 Python 程式,我們可以好心的撰寫一份 Batch file,讓朋友能夠一鍵執行 Python 程式。 :::success :book: **簡單範例** 底下只要一一複製到同一個資料夾,然後執行 run.bat 即可。 這個範例是儲存一張圖片,是什麼圖片可不能說,記得要先在 Python 安裝 requests 模組。 ::: * run.bat ```bat= @echo off start .\python\python.exe main.py ``` * main.py ```python= # 安裝 requests 模組 # .\python.exe -m pip install requests import requests url = "https://mediatrust.com/wp-content/uploads/2022/09/rick-roll-2.gif" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE" } response = requests.get(url, headers = headers) with open("picture.gif", "wb") as file: picture = response.content file.write(picture) ``` * 相對路徑圖 ``` Program/ |――――python/ | |――――python.exe | |――――... |――――run.bat |――――main.py |――――picture.gif ``` * 資料夾圖片  --- :::info 📢 **歡迎加入我的 Discord 伺服器** https://discord.gg/Jtd3eVrFJs ::: *Copyright © 2024 SmallShawn95. All rights reserved.*
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.