使用繁體中文,在w11下,使用phthon語言,要呼叫"Udp-sender.exe",這個程式,要如何指定在同個資料下的"Udp-sender.exe"的程式執行?
import subprocess
import os
# 取得當前腳本的路徑
current_directory = os.path.dirname(os.path.abspath(__file__))
# 指定可執行檔的完整路徑
exe_path = os.path.join(current_directory, 'Udp-sender.exe')
# 呼叫執行檔
subprocess.run([exe_path])
在這段程式碼中,變數 use_local 可以用來控制是使用當前資料夾中的 Udp-sender.exe 還是 C:\Windows\System32\Udp-sender.exe。根據你的邏輯設定這個變數,即可選擇要執行的程式。
import subprocess
import os
# 取得當前腳本的路徑
current_directory = os.path.dirname(os.path.abspath(__file__))
# 指定可執行檔的完整路徑
local_exe_path = os.path.join(current_directory, 'Udp-sender.exe')
system_exe_path = r'C:\Windows\System32\Udp-sender.exe'
# 判斷要使用的路徑(這裡可以根據需要進行判斷)
# 假設這裡是你自己的條件邏輯
use_local = True # 這個變數可以根據你的需求設置
if use_local:
exe_path = local_exe_path
else:
exe_path = system_exe_path
# 呼叫執行檔
subprocess.run([exe_path])
如果要將這個python檔打包在一個exe檔,並將當前資料夾中的 Udp-sender.exe一起打包進去,要如何執行?
pyinstaller --onefile --add-data "Udp-sender.exe;." main.py
--onefile: 將所有檔案打包成一個 EXE 檔。
--add-data "Udp-sender.exe;.": 指定要包含的檔案,Udp-sender.exe 是檔案名稱,;. 表示將其放在當前執行目錄下。
在 Python 腳本中,為了正確地取得 Udp-sender.exe 的路徑,你需要進行一些調整:
python
複製程式碼
import subprocess
import os
import sys
# 判斷當前執行環境
if getattr(sys, 'frozen', False):
# 如果是凍結的應用程式
current_directory = sys._MEIPASS # 這是 PyInstaller 的運行目錄
else:
# 如果是普通的 Python 腳本
current_directory = os.path.dirname(os.path.abspath(__file__))
# 指定可執行檔的完整路徑
local_exe_path = os.path.join(current_directory, 'Udp-sender.exe')
# 在這裡可以依照需要設定系統路徑
system_exe_path = r'C:\Windows\System32\Udp-sender.exe'
# 判斷要使用的路徑
use_local = True # 這個變數可以根據你的需求設置
if use_local:
exe_path = local_exe_path
else:
exe_path = system_exe_path
# 呼叫執行檔
subprocess.run([exe_path])
這樣你就可以成功地將 Python 腳本和 Udp-sender.exe 一起打包並執行了。