美化输出

This commit is contained in:
root 2024-03-30 21:07:07 +08:00
parent 9e49101e5c
commit 81805e488e
6 changed files with 121 additions and 58 deletions

41
pmpt/environment.py Normal file
View File

@ -0,0 +1,41 @@
import subprocess
import re
def get_version(command):
try:
# 使用 subprocess 调用系统命令获取版本信息
output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, universal_newlines=True)
# 使用正则表达式提取版本号
version_match = re.search(r'(\d+\.\d+(\.\d+){0,2})', output)
if version_match:
return version_match.group(1)
else:
return False
except subprocess.CalledProcessError:
return False
def getGCCver():
# 检查是否能执行 gcc 命令
return get_version('gcc --version')
def getClangVer():
# 检查是否能执行 clang 命令
return get_version('clang --version')
def getMSVCver():
# 检查是否能执行 cl 命令MSVC编译器
return get_version('cl')
def getRustVer():
process = subprocess.Popen(['rustc --version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
stdout, stderr = process.communicate()
if process.returncode == 0:
rustVer = stdout.decode().split(' ')[1]
return rustVer
else:
return False
print("GCC 版本:", getGCCver())
print("Clang 版本:", getClangVer())
print("MSVC 版本:", getMSVCver())
print('Rust版本:',getRustVer())

View File

@ -1,84 +1,94 @@
from . import util from . import util
from rich.console import Console
def search(name): from rich.table import Table
util.loadIndex() #加载索引
def search(name):
util.loadIndex() #加载索引
for Index in util.IndexList: for Index in util.IndexList:
dt = Index.packageList.get(name,None) dt = Index.packageList.get(name,None)
if dt: if dt:
return Index.IndexURL return Index.IndexURL
def main(packlist,upgrade,reads,force_reinstall,ignore_requires_python,yes): def main(packlist,upgrade,reads,force_reinstall,ignore_requires_python,yes):
console = Console()
if reads: # 从文件读取列表 if reads: # 从文件读取列表
f = open(packlist[0]) f = open(packlist[0])
packlist = f.read().split('\n') packlist = f.read().split('\n')
packsInfo = {} packsInfo = {}
print('Start installing these packages') with console.status('🚀🔍 Searching for package information...') as status:
print('Start looking for package') table = Table(show_header=True,header_style='bold')
table.add_column("Package Name", width=20,style='bold')
for rawpack in packlist: # 解析指定了版本的包名 table.add_column("Package Source", width=20,style='green')
if '==' in rawpack:
pack = rawpack.split('==')[0] for rawpack in packlist: # 解析指定了版本的包名
elif '>=' in rawpack: if '==' in rawpack:
pack = rawpack.split('>=')[0] pack = rawpack.split('==')[0]
elif '<=' in rawpack: elif '>=' in rawpack:
pack = rawpack.split('<=')[0] pack = rawpack.split('>=')[0]
elif '<' in rawpack: elif '<=' in rawpack:
pack = rawpack.split('<')[0] pack = rawpack.split('<=')[0]
elif '>' in rawpack: elif '<' in rawpack:
pack = rawpack.split('>')[0] pack = rawpack.split('<')[0]
else: elif '>' in rawpack:
pack = rawpack pack = rawpack.split('>')[0]
else:
pack = rawpack
result = search(pack.lower()) # 转小写并获取源地址
result = search(pack.lower()) # 转小写并获取源地址 packsInfo[pack] = [result,rawpack]
packsInfo[pack] = [result,rawpack]
canInstallPack = [] canInstallPack = []
for k,v in packsInfo.items(): for k,v in packsInfo.items():
if not v: if not v[0]:
print('Unable to find', k) table.add_row(k, "[red]Not found[red]")
else: else:
print(f'Find {k} from {v[0]}') table.add_row(k,v[0])
canInstallPack.append(k) canInstallPack.append(k)
console.print(table)
print('Will install',', '.join(canInstallPack))
if len(canInstallPack) < 1:
console.print('❌ [red]There are no packages available for installation.[red]')
exit()
console.print('📦 Packages to be installed:')
console.print(' '.join(canInstallPack))
while True: # 是否允许安装 while True: # 是否允许安装
if yes: if yes:
break break
ye = console.input('Proceed with installation? [Y/n]: ')
ye =input('Are you sure you want to install? (y/n)')
if ye.lower() == 'y': if ye.lower() == 'y':
break break
elif ye.lower() == 'n': elif ye.lower() == 'n':
print('User Cancels Installation') console.print('🛑 [red]User canceled the installation.[/red]')
exit() exit()
else: else:
continue continue
print('Start calling pip') console.print('🛠️ Initiating pip installation...')
for pack in canInstallPack: for pack in canInstallPack:
# 构建命令
args = [ '-i', packsInfo[pack][0]] # 指定源
# 构建命
args = [ '-i', packsInfo[pack][0]] # 指定源
if upgrade: # 升级 if upgrade: # 升级
args.append('-U') args.append('-U')
if force_reinstall: # 强制重新安装 if force_reinstall: # 强制重新安装
args.append('--force-reinstall') args.append('--force-reinstall')
if ignore_requires_python: # 忽略Python版本 if ignore_requires_python: # 忽略Python版本
args.append('--ignore-requires-python') args.append('--ignore-requires-python')
args.append(packsInfo[pack][1]) args.append(packsInfo[pack][1])
ret = util.runpip('install',args) # 运行pip ret = util.runpip('install',args) # 运行pip
if ret.returncode != 0: #是否执行完毕 if ret.returncode != 0: #是否执行完毕
print('Failed to install.') console.print('❌ [red]Installation failed.[/red]')
exit() exit()
print('Installation completed') console.print(f'✅ [green]Installation successful for {pack}[/green]')

View File

@ -3,9 +3,12 @@ from . import util
from moyanlib import jsons from moyanlib import jsons
from .install import search from .install import search
import os import os
from rich.console import Console
console = Console()
def main(name,allinfo,api_url): def main(name,allinfo,api_url):
if not search(name): if not search(name):
print('The package does not exist') console.print('❌ [red]The package does not exist[/red]')
exit() exit()
if not api_url: if not api_url:
@ -13,11 +16,11 @@ def main(name,allinfo,api_url):
req = requests.get(api_url.format(name)) req = requests.get(api_url.format(name))
if req.status_code == 404: if req.status_code == 404:
print('The package does not exist') console.print('❌ [red]The package does not exist[/red]')
exit() exit()
elif req.status_code != 200: elif req.status_code != 200:
print('Server Error!') console.print('❌ [red]Server Error![/red]')
print('Error Code:',req.status_code) console.print('[red]Error Code: '+str(req.status_code)+'[/red]')
exit() exit()

View File

@ -6,7 +6,9 @@ import os
import urllib.parse as urlparse import urllib.parse as urlparse
from hashlib import sha256 from hashlib import sha256
from .util import dirs from .util import dirs
from rich.console import Console
console = Console()
def getSourceID(url): def getSourceID(url):
''' '''
获取源id 获取源id
@ -33,7 +35,7 @@ def getIndex(url):
ClassIndex = Index(url) ClassIndex = Index(url)
print('Start parsing the HTML index for this source.') console.print('🔍 Parsing HTML index...')
for line in tqdm(HTMLIndex.split('\n')): for line in tqdm(HTMLIndex.split('\n')):
# 提取并筛选标签 # 提取并筛选标签
line_list = line.split('>') line_list = line.split('>')
@ -42,8 +44,8 @@ def getIndex(url):
ClassIndex.addPackage(package_name) # 添加包 ClassIndex.addPackage(package_name) # 添加包
print('This source has a total of', ClassIndex.number,'packages.') console.print('Total number of packages:', str(ClassIndex.number))
print('Start saving the index for this source.') console.print('📚 Saving index..."')
dill.dump(ClassIndex,open(f'{dirs.user_data_dir}/Index/{getSourceID(url)}.pidx','wb')) dill.dump(ClassIndex,open(f'{dirs.user_data_dir}/Index/{getSourceID(url)}.pidx','wb'))
def getAllIndex(): def getAllIndex():
@ -55,11 +57,11 @@ def getAllIndex():
''' '''
SourceList = jsons.load(open(os.path.join(dirs.user_config_dir,'Source.json'))) # 加载源列表 SourceList = jsons.load(open(os.path.join(dirs.user_config_dir,'Source.json'))) # 加载源列表
if len(SourceList) < 1: if len(SourceList) < 1:
print('You have not configured any sources.') console.print('❌ [red]You have not configured any sources.[/red]')
exit(1) exit(1)
for url in SourceList: # 遍历源列表 for url in SourceList: # 遍历源列表
print('Start downloading index from', url) console.print('📚 Downloading index from', url+'...')
getIndex(url) getIndex(url)
print() console.print('✅ [green]Index downloaded successfully![/green]')

View File

@ -1,8 +1,10 @@
#pylint:disable=W0622
import os import os
from subprocess import Popen,PIPE from subprocess import Popen,PIPE
import sys import sys
import pathlib import pathlib
import dill import dill
from rich import print
import time import time
from platformdirs import PlatformDirs from platformdirs import PlatformDirs
@ -24,6 +26,7 @@ def loadIndex():
加载索引 加载索引
''' '''
if len(IndexList) == 0: # 判断是否为空 if len(IndexList) == 0: # 判断是否为空
print('🔍 Loading index...')
IndexDir = pathlib.Path(os.path.join(dirs.user_data_dir,'Index')) IndexDir = pathlib.Path(os.path.join(dirs.user_data_dir,'Index'))
for i in IndexDir.iterdir(): # 遍历索引文件夹 for i in IndexDir.iterdir(): # 遍历索引文件夹
IndexFile = dill.load(open(i,'rb')) # 加载索引 IndexFile = dill.load(open(i,'rb')) # 加载索引
@ -32,17 +35,20 @@ def loadIndex():
if len(IndexList) == 0: if len(IndexList) == 0:
raise FileNotFoundError('No index. Run "pmpt update" first to update the index') raise FileNotFoundError('No index. Run "pmpt update" first to update the index')
def runpip(command,other=[]) -> Popen: def runpip(command,other=None,dbg=False) -> Popen:
''' '''
运行pip 运行pip
''' '''
if not other:
other = []
baseCommand = [sys.executable,'-m','pip'] baseCommand = [sys.executable,'-m','pip']
baseCommand.append(command) baseCommand.append(command)
Command = baseCommand + other Command = baseCommand + other
if dbg:
print(' '.join(Command)) print('Command to be run:',' '.join(Command))
runClass = Popen(Command) runClass = Popen(Command)
runClass.wait() runClass.wait()
return runClass return runClass

View File

@ -3,4 +3,5 @@ requests
moyanlib moyanlib
click click
dill dill
tqdm tqdm
rich