pyenv-virtualenv for Windows 1.2
A 'pyenv' plugin to manage Python virtual environments, depending on different Python versions, for various Python projects.
Loading...
Searching...
No Matches
pyenv-virtualenvs.py
Go to the documentation of this file.
1##
2# @package pyenv-virtualenvs
3# @file pyenv-virtualenvs.py
4# @author Michael Paul Korthals
5# @date 2025-07-10
6# @version 1.0.0
7# @copyright © 2025 Michael Paul Korthals. All rights reserved.
8# See License details in the documentation.
9#
10# Utility application to list the installed Python versions and
11# virtual environments. In addition the Project properties will
12# be listed and its locations will be displayed in a folder tree.
13#
14
15# --- IMPORTS ----------------------------------------------------------
16
17# Python
18import argparse
19import os
20import sys
21
22# Avoid colored output problems
23os.system('')
24
25# Community
26try:
27 import virtualenv
28except ImportError():
29 print(
30 '\x1b[101mCRITICAL %s\x1b[0m'
31 %
32 'Cannot find package "%s".'
33 %
34 'virtualenv'
35 )
36 print(
37 '\x1b[37mINFO %s\x1b[0m'
38 %
39 'Install it using "pip". Then try again.')
40 import virtualenv
41
42# My
43import lib.hlp as hlp
44import lib.log as log
45import lib.tbl as tbl
46
47
48# --- RUN ---------------------------------------------------------------
49
50## Sub routine to run the application.
51#
52# @return RC = 0 or other values in case of error.
53def run() -> int:
54 rc: int = 0
55 cwd = os.getcwd()
56 # noinspection PyBroadException
57 try:
58 while True:
60 'Listing Python virtual environments in "pyenv".'
61 )
62 log.verbose('Determining Python versions ...')
63 # Determine Python version, which is capable
64 # to install Python virtual environment.
65 versions_dir = os.path.join(
66 os.environ['PYENV_ROOT'],
67 'versions'
68 )
69 if not os.path.isdir(versions_dir):
70 log.error('Cannot find any Python version in "pyenv".')
71 log.info('Install a Python version 3.3+ into "pyenv".')
72 rc = 1
73 break
75 '*',
76 venv_capable=False,
77 as_paths=True
78 )
79 if len(vers) == 0:
80 log.error('Cannot find a Python version in "pyenv".')
81 log.info('Install a Python version 3.3+ into "pyenv".')
82 rc = 1
83 break
84 per = os.environ['PYENV_ROOT']
85 # Pass 1: Collect the Python versions.
86 pyts = [
87 [tbl.HEADER, 'G', 'Venv-Capable', 'Version', '"pyenv" Location'],
88 [tbl.SEPARATOR]
89 ]
90 for ver in vers:
91 pyts_item = [
92 tbl.DATA,
95 os.path.basename(ver),
96 '%PYENV_ROOT%' + os.sep + ver[len(per):]
97 ]
98 pyts.append(pyts_item)
99 # End for
100 pyts.append([tbl.SEPARATOR])
101 # Pass 2: Collect the virtual environments.
102 pves = [
103 [tbl.HEADER, 'A', 'Version', 'Name', '"pyenv" Location'],
104 [tbl.SEPARATOR]
105 ]
106 for ver in vers:
107 venvs = hlp.getEnvs(ver,'*', as_paths=True)
108 for venv in venvs:
109 act = ' '
110 if (
111 ('PROMPT' in os.environ)
112 and
113 (f'({os.path.basename(venv)})' in os.environ['PROMPT'])
114 ):
115 act = '*'
116 pves.append([
117 tbl.DATA,
118 act,
119 os.path.basename(ver),
120 os.path.basename(venv),
121 '%PYENV_ROOT%' + os.sep + venv[len(per):]
122 ])
123 # End for
124 pves.append([tbl.SEPARATOR])
125 # Pass 3: Output list of Python versions.
126 table_pyts = tbl.SimpleTable(
127 pyts,
128 headline='INSTALLED PYTHON VERSIONS (G = global):'
129 )
130 table_pyts.run()
131 # Pass 4: Output list of virtual environments.
132 table_pves = tbl.SimpleTable(
133 pves,
134 headline='AVAILABLE PYTHON VIRTUAL ENVIRONMENTS (A = active):'
135 )
136 table_pves.run()
137 # Output list of project properties (if exists)
139 log.verbose(f'Done (RC = {rc}).')
140 # Go on
141 break
142 # End while
143 except:
144 log.error(sys.exc_info())
145 rc = 1
146 finally:
147 os.chdir(cwd)
148 return rc
149
150
151# --- MAIN --------------------------------------------------------------
152
153## Parse CLI arguments for this application.<br>
154# <br>
155# Implement this as required, but don't touch the interface definition
156# for input and output.
157#
158# @return A tuple of:
159# * Namespace to read arguments in "dot" notation or None
160# in case of help or error.
161# * RC = 0 or another value in case of error.
162def parseCliArguments() -> tuple[(argparse.Namespace, None), int]:
163 rc: int = 0
164 # noinspection PyBroadException
165 try:
166 parser = argparse.ArgumentParser(
167# --- BEGIN CHANGE -----------------------------------------------------
168 prog='pyenv virtualenvs',
169 description='Output lists of Python versions, virtual environments and related project properties.'
170 )
171# --- END CHANGE -------------------------------------------------------
172 return parser.parse_args(), rc
173 except SystemExit:
174 return None, 0 # -h, --help
175 except:
176 log.error(sys.exc_info())
177 return None, 1
178
179## Main routine of the application.
180#
181# @return RC = 0 or other values in case of error.
182def main() -> int:
183 # noinspection PyBroadException
184 try:
185 while True:
186 # Audit the operating system platform
187 rc = hlp.auditPlatform('Windows')
188 if rc != 0:
189 # Deviation: Reject unsupported platform
190 break
191 # Audit the global Python version number
193 if rc != 0:
194 # Deviation: Reject unsupported Python version
195 break
196 # Initialize the colored logging to console
198 # Audit the "pyenv" version number
199 rc = hlp.auditPyEnv('3')
200 if rc != 0:
201 # Deviation: Reject unsupported "pyenv" version
202 break
203 # Parse arguments
204 log.verbose('Parsing arguments ...')
205 args, rc = parseCliArguments()
206 if rc != 0:
207 break
208 if args is None: # -h, --help
209 break
210 # Run this application
211 log.verbose('Running application ...')
212 rc = run()
213 if rc != 0:
214 break
215 # Go on
216 break
217 # End while
218 except Exception as exc:
220 log.error(sys.exc_info())
221 else:
222 print(
223 '\x1b[91mERROR: Unexpected error "%s".\x1b[0m'
224 %
225 str(exc)
226 )
227 rc = 1
228 return rc
229
230
231if __name__ == "__main__":
232 sys.exit(main())
233
234# --- END OF CODE ------------------------------------------------------
235
int auditPyEnv(str min_ver)
Check if "pyenv" version is greater or equal the given minimal version.
Definition hlp.py:213
int auditGlobalPythonVersion(str min_ver)
Check if Python version is greater or equal the given minimal version.
Definition hlp.py:148
int auditPlatform(str name)
Check if the program in running on the required platform.
Definition hlp.py:85
str getGlobalStar(str ver)
Get the "*" marker for this version, if it is the globally selected version in "pyenv".
Definition hlp.py:375
list[str] getEnvs(str ver, str name=' *', bool as_paths=False)
Get list of installed virtual environments for a specific Python version in "pyenv".
Definition hlp.py:718
int listProjectProperties()
Display the table, which shows a list about project properties.
Definition hlp.py:866
list[str] getPythonVersions(str version=' *', bool venv_capable=False, bool as_paths=False)
Get list of installed Python version directories in "pyenv".
Definition hlp.py:500
str getColoredVenvCapability(str ver)
Get the colored virtual environment capability str for the specific version number or path.
Definition hlp.py:481
verbose((str, tuple) msg)
Log verbose message colored to console only.
Definition log.py:209
initLogging()
Initialize the logging.
Definition log.py:71
bool isInitialized()
Definition log.py:90
info((str, tuple) msg)
Log info message colored to console only.
Definition log.py:203
error((str, tuple) msg)
Log error message colored to console only.
Definition log.py:179
int run()
Sub routine to run the application.
int main()
Main routine of the application.
tuple[(argparse.Namespace, None), int] parseCliArguments()
Parse CLI arguments for this application.