1 回答

TA貢獻1810條經驗 獲得超4個贊
我們需要牢記以下兩件事:
pyinstaller 選項
源代碼中驅動程序的路徑
Chromedriver.exe 是一個二進制文件,因此,我們可以使用--add binary我在問題中提到的方式將其添加到 Pyinstaller 中。因此,我們在 cmd 中的 pyinstaller 命令將是這樣的:
pyinstaller --noconfirm --onefile --console --icon "path/to/icon.ico" --add-binary "path/to/chrome/driver;./driver" "path/to/the/python/pythonscript.py"
其次,我們需要以這樣的方式修改源代碼,使其既不會損害Python控制臺中的代碼,也不會損害轉換后的可執行文件中的代碼。因此,我們需要將driver_path代碼更改為
driver = webdriver.Chrome('path/to/chromedriver.exe', options=Options())
像這樣的事情
import os
import sys
def resource_path(another_way):
try:
usual_way = sys._MEIPASS # When in .exe, this code is executed, that enters temporary directory that is created automatically during runtime.
except Exception:
usual_way = os.path.dirname(__file__) # When the code in run from python console, it runs through this exception.
return os.path.join(usual_way, another_way)
driver = webdriver.Chrome(resource_path('./driver/chromedriver.exe'), options=Options())
我們編寫該Exception部分是為了使其能夠與 python 控制臺一起工作。如果僅以 .exe 格式運行是主要目標,那么我們也可以忽略 Exception 部分。
當我們嘗試從類中_MEIPASS訪問受保護的成員時,此代碼會在 python 控制臺中拋出警告。除此之外,突出顯示sys.pyi的是找不到引用。_MEIPASS
添加回答
舉報