最近在學習python,由于不同的版本之間的差距較大,如果是用環境變量來配置python的話,會需要來回改,于是請教得知可以用conda來管理,但是conda在管理的時候老是要輸入命令,感覺也很煩,于是讓gpt幫寫了一個很簡陋的conda環境管理界面(純屬個人學習,不喜勿噴),下面是最終的效果:
1、左側的激活按鈕沒什么用
2、中間的輸入框是要安裝的包名,輸入完成之后,點擊安裝即可把包安裝到對應的環境,比如我在ai312對應的輸入框中輸入numpy,那么就是在a312這個env下面安裝numpy的包,其實背后執行的命令就是:conda install numpy -n ai312 -y
3、下面的兩個輸入框,第一個是環境名稱,比如ai312,第二個是python的版本,比如3.8
直接上代碼:
import os
import subprocess
import json
import re
import tkinter as tk
from tkinter import messagebox, simpledialog
from tkinter import scrolledtext
import threadingclass CondaEnvManager:def __init__(self, root):self.root = rootself.root.title("Conda 環境管理器")self.root.geometry("600x400")# 獲取 Conda 路徑self.conda_path = self.get_conda_path()self.env_list_frame = tk.Frame(self.root)self.env_list_frame.pack(pady=10, fill=tk.BOTH, expand=True)self.create_env_frame = tk.Frame(self.root)self.create_env_frame.pack(pady=10)self.create_env_label = tk.Label(self.create_env_frame, text="創建新環境:")self.create_env_label.grid(row=0, column=0, padx=5)self.new_env_name = tk.Entry(self.create_env_frame)self.new_env_name.grid(row=0, column=1, padx=5)# 新增 Python 版本輸入框self.python_version_label = tk.Label(self.create_env_frame, text="Python 版本:")self.python_version_label.grid(row=1, column=0, padx=5)self.python_version_entry = tk.Entry(self.create_env_frame)self.python_version_entry.grid(row=1, column=1, padx=5)self.create_env_button = tk.Button(self.create_env_frame, text="創建", command=self.create_env)self.create_env_button.grid(row=0, column=2, padx=5)self.refresh_envs()# 日志輸出框self.log_output = scrolledtext.ScrolledText(self.root, width=70, height=15)self.log_output.pack(pady=10, fill=tk.BOTH, expand=True)def get_conda_path(self):# 提示用戶輸入 Conda 路徑while True:conda_path = simpledialog.askstring("Conda 路徑", "請輸入 conda.exe 的完整路徑:")if not conda_path:messagebox.showerror("錯誤", "Conda 路徑不能為空,請重試。")continue# 檢查路徑是否有效if os.path.isfile(conda_path) and "conda" in conda_path:return conda_pathelse:messagebox.showerror("錯誤", f"路徑 '{conda_path}' 無效,請重試。")def refresh_envs(self):for widget in self.env_list_frame.winfo_children():widget.destroy()try:# 使用用戶輸入的 Conda 路徑result = subprocess.run([self.conda_path, 'env', 'list', '--json'], capture_output=True, text=True)output = result.stdout# 提取 JSON 數據try:json_match = re.search(r'\{.*\}', output, re.DOTALL)if not json_match:raise ValueError("No valid JSON data found in the output.")json_data = json_match.group(0)data = json.loads(json_data)except json.JSONDecodeError as e:messagebox.showerror("錯誤", f"解析 JSON 數據失敗: {e}")returnexcept ValueError as e:messagebox.showerror("錯誤", f"提取 JSON 數據失敗: {e}")returnenvs = data.get('envs', [])if not envs:messagebox.showinfo("信息", "未找到任何環境。")returnfor env in envs:env_name = os.path.basename(env)env_frame = tk.Frame(self.env_list_frame)env_frame.pack(pady=5, fill=tk.X)# 激活按鈕放到左邊activate_button = tk.Button(env_frame, text="激活", command=lambda e=env_name: self.activate_env(e))activate_button.pack(side=tk.LEFT, padx=5)# 環境名稱標簽env_label = tk.Label(env_frame, text=env_name, anchor="w", width=20)env_label.pack(side=tk.LEFT, padx=5)# 輸入框居中并拉長package_entry = tk.Entry(env_frame, width=30)package_entry.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)# 安裝按鈕放到右邊install_button = tk.Button(env_frame, text="安裝", command=lambda e=env_name, p=package_entry: self.start_installation(e, p.get()))install_button.pack(side=tk.RIGHT, padx=5)except Exception as e:messagebox.showerror("錯誤", f"獲取環境失敗: {e}")def start_installation(self, env_name, package_name):if not package_name:messagebox.showwarning("警告", "請輸入包名。")returnself.log_output.delete(1.0, tk.END)threading.Thread(target=self.install_package, args=(env_name, package_name)).start()def install_package(self, env_name, package_name):try:process = subprocess.Popen([self.conda_path, 'install', package_name, '-n', env_name, '-y'],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)for line in process.stdout:self.log_output.insert(tk.END, line)self.log_output.see(tk.END)process.wait()messagebox.showinfo("成功", f"在 {env_name} 中安裝了 {package_name}。")except subprocess.CalledProcessError as e:messagebox.showerror("錯誤", f"安裝包失敗: {e}")def activate_env(self, env_name):subprocess.run([self.conda_path, 'activate', env_name], check=True)messagebox.showinfo("激活", f"激活環境: {env_name}")def create_env(self):env_name = self.new_env_name.get().strip()python_version = self.python_version_entry.get().strip() # 獲取輸入的 Python 版本if not env_name:messagebox.showwarning("警告", "請輸入新環境的名稱。")returnif not python_version:messagebox.showwarning("警告", "請輸入 Python 版本。")returntry:subprocess.run([self.conda_path, 'create', '--name', env_name, f'python={python_version}', '-y'], check=True)messagebox.showinfo("成功", f"創建新環境: {env_name},Python 版本: {python_version}。")self.new_env_name.delete(0, tk.END)self.python_version_entry.delete(0, tk.END) # 清空 Python 版本輸入框self.refresh_envs()except subprocess.CalledProcessError as e:messagebox.showerror("錯誤", f"創建環境失敗: {e}")if __name__ == "__main__":root = tk.Tk()app = CondaEnvManager(root)root.mainloop()
最后通過執行:pyinstaller --onefile --windowed Conda.py,打包成可執行的exe文件即可
啟動的時候需要輸入conda所在目錄(本來我是想通過環境變量來設置,但是代碼里面讀取不到,于是就采取這種本方法了),比如我的conda安裝在:
那么啟動時輸入:?D:/install/anaconda3/condabin/conda.bat
PS:需要先安裝??pyinstaller和anaconda(或者miniconda),pyinstaller可以用pip安裝(pip install pyinstaller),conda的安裝就不在這里說了,跟普通的軟件安裝一樣,一直下一步即可
然后就是如何使用已經創建好的環境了,此處以pycharm為例,比如我創建了一個ai312的環境,那么在conda的安裝目錄的envs目錄下面就會生成一個ai312的目錄:
在pycharm里面選擇這個python.exe文件: