Python虚拟环境(Python venv)的创建、激活、退出及删除
    		       		warning:
    		            这篇文章距离上次修改已过446天,其中的内容可能已经有所变动。
    		        
        		                
                
import os
import subprocess
 
# 创建虚拟环境
def create_venv(venv_name: str, python_executable: str = 'python3'):
    subprocess.check_call([python_executable, '-m', 'venv', venv_name])
 
# 激活虚拟环境
def activate_venv(venv_name: str):
    script_name = 'Scripts\\activate' if os.name == 'nt' else 'bin\\activate'
    activate_path = os.path.join(venv_name, script_name)
    print(f"激活虚拟环境: {activate_path}")
    os.system(f". {activate_path}")
 
# 退出虚拟环境
def deactivate_venv():
    print("退出虚拟环境")
    os.system("deactivate")
 
# 删除虚拟环境
def delete_venv(venv_name: str, python_executable: str = 'python3'):
    subprocess.check_call([python_executable, '-m', 'venv', '--clear', venv_name])
    os.rmdir(venv_name)
 
# 示例使用
create_venv('my_venv')
activate_venv('my_venv')
# 在虚拟环境中进行操作...
deactivate_venv()
delete_venv('my_venv')这段代码提供了创建、激活、退出及删除Python虚拟环境的函数。使用标准库中的subprocess.check_call来创建虚拟环境,并通过调用对应的激活脚本来激活环境。退出虚拟环境通过运行deactivate命令,删除虚拟环境时使用python3 -m venv --clear命令清除环境状态后,再删除文件夹。
评论已关闭