PAT1016 BASIC:部分A+B (15)

本文介绍了一个简单的程序设计问题——1016.部分A+B,任务是根据给定的两个正整数及其指定的部分数字,计算并输出这两个数字的部分之和。文章提供了完整的代码实现。

1016. 部分A+B (15)

时间限制
100 ms
内存限制
32000 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue

正整数A的“DA(为1位整数)部分”定义为由A中所有DA组成的新整数PA。例如:给定A = 3862767,DA = 6,则A的“6部分”PA是66,因为A中有2个6。

现给定A、DA、B、DB,请编写程序计算PA + PB

输入格式:

输入在一行中依次给出A、DA、B、DB,中间以空格分隔,其中0 < A, B < 1010

输出格式:

在一行中输出PA + PB的值。

输入样例1:
3862767 6 13530293 3
输出样例1:
399
输入样例2:
3862767 1 13530293 8
输出样例2:
0

//============code============//
#include<stdio.h>
#include<math.h>
int cout(int a,int b)
{
    int num=0;
    int i=0;
    while(a>9)
    {
        if(a%10==b) num+=b*pow(10,i),i++;
        a/=10;
    }
    if(a==b) num+=b*pow(10,i);
    return num;
}
int main()
{
    int a,da,b,db;
    int pa=0,pb=0;
    scanf("%d%d%d%d",&a,&da,&b,&db);
    printf("%d\n",cout(a,da)+cout(b,db));
    return 0;
}
PS C:\Users\Administrator\Desktop> function Repair-PythonSite { >> param( >> [string]$PythonPath = "E:\Python310" >> ) >> >> # 1. 定位关键目录 >> $libPath = "$PythonPath\Lib" >> $sitePackages = "$PythonPath\Lib\site-packages" >> >> # 2. 彻底移除所有自定义文件 >> $filesToRemove = @( >> "$libPath\sitecustomize.py", >> "$libPath\sitecustomize.pyc", >> "$sitePackages\environment-helper.pth", >> "$sitePackages\environment_helper.py", >> "$sitePackages\distutils-precedence.pth" >> ) >> >> foreach ($file in $filesToRemove) { >> if (Test-Path $file) { >> Remove-Item $file -Force -ErrorAction SilentlyContinue >> Write-Host "🧹 Removed: $file" -ForegroundColor Yellow >> } >> } >> >> # 3. 修复原始site.py文件 >> $sitePath = "$libPath\site.py" >> if (Test-Path $sitePath) { >> # 备份原始文件 >> Copy-Item $sitePath "$sitePath.bak" -Force >> >> # 修复编码问题 >> $content = [System.IO.File]::ReadAllText($sitePath, [System.Text.Encoding]::UTF8) >> $content = $content -replace "for n, line in enumerate\(f\):", @" >> # Fixed encoding handling >> try: >> content = f.read() >> except UnicodeDecodeError: >> f.close() >> f = open(fullname, encoding='utf-8') >> content = f.read() >> lines = content.splitlines() >> for n, line in enumerate(lines): >> "@ >> >> [System.IO.File]::WriteAllText($sitePath, $content, [System.Text.Encoding]::UTF8) >> Write-Host "🔧 Repaired site.py encoding handling" -ForegroundColor Cyan >> } >> >> # 4. 创建安全的sitecustomize.py >> $safeSiteCustomize = @' >> # SAFE SITECUSTOMIZE >> import sys >> import os >> >> def safe_pth_handler(pth_file): >> """Safe .pth file handler with encoding fallback""" >> try: >> with open(pth_file, 'r', encoding='utf-8') as f: >> content = f.read() >> except UnicodeDecodeError: >> try: >> with open(pth_file, 'r', encoding='latin-1') as f: >> content = f.read() >> except: >> return False >> >> # Basic validation >> if "exec" in content or "compile" in content: >> return False >> >> # Only allow simple path additions >> lines = [line.strip() for line in content.splitlines() if line.strip()] >> for line in lines: >> if line.startswith(('import', 'sys.', 'os.')): >> return False >> >> # Add valid paths >> for line in lines: >> if os.path.exists(line): >> sys.path.insert(0, line) >> >> return True >> >> # Restore original handler >> if hasattr(sys, "__orig_site_pth_handler"): >> sys._pth_handler = sys.__orig_site_pth_handler >> else: >> # Create backup of original handler >> sys.__orig_site_pth_handler = sys._pth_handler >> '@ >> >> [System.IO.File]::WriteAllText("$libPath\sitecustomize.py", $safeSiteCustomize, [System.Text.Encoding]::UTF8) >> Write-Host "🔧 Created safe sitecustomize.py" -ForegroundColor Cyan >> >> # 5. 验证修复 >> Write-Host "🔄 Testing Python environment..." -ForegroundColor Cyan >> python -S -c "import site; print('✅ Site module loaded successfully')" >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> function Test-PythonEnvironment { >> param( >> [string]$PythonPath = "E:\Python310" >> ) >> >> # 1. 测试基本功能 >> $basicTest = python -c "import sys; print(f'Python version: {sys.version.split()[0]}')" >> Write-Host $basicTest >> >> # 2. 测试模块导入 >> $moduleTest = python -c @" >> try: >> import site, os, sys >> print('✅ Core modules imported') >> >> # Test sitecustomize >> site_dir = os.path.dirname(site.__file__) >> sitecustomize_path = os.path.join(site_dir, 'sitecustomize.py') >> if os.path.exists(sitecustomize_path): >> print(f'✅ sitecustomize.py exists: {sitecustomize_path}') >> else: >> print('⚠️ sitecustomize.py not found') >> except Exception as e: >> print(f'❌ Error: {e}') >> "@ >> Write-Host $moduleTest >> >> # 3. 测试.pth文件处理 >> $pthTest = python -c @" >> import tempfile >> with tempfile.NamedTemporaryFile(suffix='.pth', delete=False) as tmp: >> tmp.write(b'test_path\n') >> pth_path = tmp.name >> >> try: >> import site >> site.addsitedir(os.path.dirname(pth_path)) >> print('✅ .pth file processed successfully') >> finally: >> os.unlink(pth_path) >> "@ >> Write-Host $pthTest >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 执行修复 PS C:\Users\Administrator\Desktop> Repair-PythonSite -PythonPath "E:\Python310" 🧹 Removed: E:\Python310\Lib\sitecustomize.py 🔧 Repaired site.py encoding handling 🔧 Created safe sitecustomize.py 🔄 Testing Python environment... ✅ Site module loaded successfully PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 重启PowerShell会话 PS C:\Users\Administrator\Desktop> Write-Host "`n🔄 Please restart PowerShell session for changes to take effect" -ForegroundColor Yellow 🔄 Please restart PowerShell session for changes to take effect PS C:\Users\Administrator\Desktop> Write-Host "Close this window and open a new one" -ForegroundColor Yellow Close this window and open a new one PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 在新会话中测试 PS C:\Users\Administrator\Desktop> Test-PythonEnvironment -PythonPath "E:\Python310" Error in sitecustomize; set PYTHONVERBOSE for traceback: AttributeError: module 'sys' has no attribute '_pth_handler' Python version: 3.10.10 Error in sitecustomize; set PYTHONVERBOSE for traceback: AttributeError: module 'sys' has no attribute '_pth_handler' Traceback (most recent call last): File "<string>", line 3, in <module> UnicodeEncodeError: 'gbk' codec can't encode character '\u2705' in position 0: illegal multibyte sequence During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 13, in <module> UnicodeEncodeError: 'gbk' codec can't encode character '\u274c' in position 0: illegal multibyte sequence Error in sitecustomize; set PYTHONVERBOSE for traceback: AttributeError: module 'sys' has no attribute '_pth_handler' Traceback (most recent call last): File "<string>", line 8, in <module> NameError: name 'os' is not defined During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 11, in <module> NameError: name 'os' is not defined PS C:\Users\Administrator\Desktop> function Repair-PythonSite { >> param( >> [string]$PythonPath = "E:\Python310" >> ) >> >> # 1. 定位关键目录 >> $libPath = "$PythonPath\Lib" >> $sitePackages = "$PythonPath\Lib\site-packages" >> >> # 2. 彻底移除所有自定义文件 >> $filesToRemove = @( >> "$libPath\sitecustomize.py", >> "$libPath\sitecustomize.pyc", >> "$sitePackages\environment-helper.pth", >> "$sitePackages\environment_helper.py", >> "$sitePackages\distutils-precedence.pth" >> ) >> >> foreach ($file in $filesToRemove) { >> if (Test-Path $file) { >> Remove-Item $file -Force -ErrorAction SilentlyContinue >> Write-Host "🧹 Removed: $file" -ForegroundColor Yellow >> } >> } >> >> # 3. 修复原始site.py文件 >> $sitePath = "$libPath\site.py" >> if (Test-Path $sitePath) { >> # 备份原始文件 >> Copy-Item $sitePath "$sitePath.bak" -Force >> >> # 修复编码问题 >> $content = [System.IO.File]::ReadAllText($sitePath, [System.Text.Encoding]::UTF8) >> $content = $content -replace "for n, line in enumerate\(f\):", @" >> # Fixed encoding handling >> try: >> content = f.read() >> except UnicodeDecodeError: >> f.close() >> f = open(fullname, encoding='utf-8') >> content = f.read() >> lines = content.splitlines() >> for n, line in enumerate(lines): >> "@ >> >> [System.IO.File]::WriteAllText($sitePath, $content, [System.Text.Encoding]::UTF8) >> Write-Host "🔧 Repaired site.py encoding handling" -ForegroundColor Cyan >> } >> >> # 4. 创建安全的sitecustomize.py >> $safeSiteCustomize = @' >> # SAFE SITECUSTOMIZE >> import sys >> import os >> >> def safe_pth_handler(pth_file): >> """Safe .pth file handler with encoding fallback""" >> try: >> with open(pth_file, 'r', encoding='utf-8') as f: >> content = f.read() >> except UnicodeDecodeError: >> try: >> with open(pth_file, 'r', encoding='latin-1') as f: >> content = f.read() >> except: >> return False >> >> # Basic validation >> if "exec" in content or "compile" in content: >> return False >> >> # Only allow simple path additions >> lines = [line.strip() for line in content.splitlines() if line.strip()] >> for line in lines: >> if line.startswith(('import', 'sys.', 'os.')): >> return False >> >> # Add valid paths >> for line in lines: >> if os.path.exists(line): >> sys.path.insert(0, line) >> >> return True >> >> # Restore original handler >> if hasattr(sys, "__orig_site_pth_handler"): >> sys._pth_handler = sys.__orig_site_pth_handler >> else: >> # Create backup of original handler >> sys.__orig_site_pth_handler = sys._pth_handler >> '@ >> >> [System.IO.File]::WriteAllText("$libPath\sitecustomize.py", $safeSiteCustomize, [System.Text.Encoding]::UTF8) >> Write-Host "🔧 Created safe sitecustomize.py" -ForegroundColor Cyan >> >> # 5. 验证修复 >> Write-Host "🔄 Testing Python environment..." -ForegroundColor Cyan >> python -S -c "import site; print('✅ Site module loaded successfully')" >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> function Test-PythonEnvironment { >> param( >> [string]$PythonPath = "E:\Python310" >> ) >> >> # 1. 测试基本功能 >> $basicTest = python -c "import sys; print(f'Python version: {sys.version.split()[0]}')" >> Write-Host $basicTest >> >> # 2. 测试模块导入 >> $moduleTest = python -c @" >> try: >> import site, os, sys >> print('✅ Core modules imported') >> >> # Test sitecustomize >> site_dir = os.path.dirname(site.__file__) >> sitecustomize_path = os.path.join(site_dir, 'sitecustomize.py') >> if os.path.exists(sitecustomize_path): >> print(f'✅ sitecustomize.py exists: {sitecustomize_path}') >> else: >> print('⚠️ sitecustomize.py not found') >> except Exception as e: >> print(f'❌ Error: {e}') >> "@ >> Write-Host $moduleTest >> >> # 3. 测试.pth文件处理 >> $pthTest = python -c @" >> import tempfile >> with tempfile.NamedTemporaryFile(suffix='.pth', delete=False) as tmp: >> tmp.write(b'test_path\n') >> pth_path = tmp.name >> >> try: >> import site >> site.addsitedir(os.path.dirname(pth_path)) >> print('✅ .pth file processed successfully') >> finally: >> os.unlink(pth_path) >> "@ >> Write-Host $pthTest >> } PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 执行修复 PS C:\Users\Administrator\Desktop> Repair-PythonSite -PythonPath "E:\Python310" 🧹 Removed: E:\Python310\Lib\sitecustomize.py 🔧 Repaired site.py encoding handling 🔧 Created safe sitecustomize.py 🔄 Testing Python environment... ✅ Site module loaded successfully PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 重启PowerShell会话 PS C:\Users\Administrator\Desktop> Write-Host "`n🔄 Please restart PowerShell session for changes to take effect" -ForegroundColor Yellow 🔄 Please restart PowerShell session for changes to take effect PS C:\Users\Administrator\Desktop> Write-Host "Close this window and open a new one" -ForegroundColor Yellow Close this window and open a new one PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 在新会话中测试 PS C:\Users\Administrator\Desktop> Test-PythonEnvironment -PythonPath "E:\Python310" Error in sitecustomize; set PYTHONVERBOSE for traceback: AttributeError: module 'sys' has no attribute '_pth_handler' Python version: 3.10.10 Error in sitecustomize; set PYTHONVERBOSE for traceback: AttributeError: module 'sys' has no attribute '_pth_handler' Traceback (most recent call last): File "<string>", line 3, in <module> UnicodeEncodeError: 'gbk' codec can't encode character '\u2705' in position 0: illegal multibyte sequence During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 13, in <module> UnicodeEncodeError: 'gbk' codec can't encode character '\u274c' in position 0: illegal multibyte sequence Error in sitecustomize; set PYTHONVERBOSE for traceback: AttributeError: module 'sys' has no attribute '_pth_handler' Traceback (most recent call last): File "<string>", line 8, in <module> NameError: name 'os' is not defined During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 11, in <module> NameError: name 'os' is not defined PS C:\Users\Administrator\Desktop> # site.py 安全补丁 (添加到文件末尾) PS C:\Users\Administrator\Desktop> import os import : 无法将“import”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 1 + import os + ~~~~~~ + CategoryInfo : ObjectNotFound: (import:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> def safe_audit_hook(event, args): 所在位置 行:1 字符: 26 + def safe_audit_hook(event, args): + ~ 参数列表中缺少参量。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingArgument PS C:\Users\Administrator\Desktop> if event == "import" and "sitecustomize" in args[0]: 所在位置 行:1 字符: 7 + if event == "import" and "sitecustomize" in args[0]: + ~ if 语句中的“if”后面缺少“(”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingOpenParenthesisInIfStatement PS C:\Users\Administrator\Desktop> # Validate sitecustomize.py PS C:\Users\Administrator\Desktop> sitecustomize_path = None sitecustomize_path : 无法将“sitecustomize_path”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 9 + sitecustomize_path = None + ~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (sitecustomize_path:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> for path in sys.path: 所在位置 行:1 字符: 12 + for path in sys.path: + ~ 关键字“for”后面缺少左“(”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingOpenParenthesisAfterKeyword PS C:\Users\Administrator\Desktop> candidate = os.path.join(path, "sitecustomize.py") 所在位置 行:1 字符: 42 + candidate = os.path.join(path, "sitecustomize.py") + ~ 参数列表中缺少参量。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingArgument PS C:\Users\Administrator\Desktop> if os.path.exists(candidate): 所在位置 行:1 字符: 15 + if os.path.exists(candidate): + ~ if 语句中的“if”后面缺少“(”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingOpenParenthesisInIfStatement PS C:\Users\Administrator\Desktop> sitecustomize_path = candidate sitecustomize_path : 无法将“sitecustomize_path”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 17 + sitecustomize_path = candidate + ~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (sitecustomize_path:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> break PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> if sitecustomize_path: 所在位置 行:1 字符: 11 + if sitecustomize_path: + ~ if 语句中的“if”后面缺少“(”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingOpenParenthesisInIfStatement PS C:\Users\Administrator\Desktop> try: try: : 无法将“try:”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 13 + try: + ~~~~ + CategoryInfo : ObjectNotFound: (try::String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> with open(sitecustomize_path, "r", encoding="utf-8") as f: 所在位置 行:1 字符: 45 + with open(sitecustomize_path, "r", encoding="utf-8") ... + ~ 参数列表中缺少参量。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingArgument PS C:\Users\Administrator\Desktop> content = f.read() 所在位置 行:1 字符: 38 + content = f.read() + ~ “(”后面应为表达式。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ExpectedExpression PS C:\Users\Administrator\Desktop> # Basic security checks PS C:\Users\Administrator\Desktop> if "exec(" in content or "compile(" in content: 所在位置 行:1 字符: 23 + if "exec(" in content or "compile(" in content: + ~ if 语句中的“if”后面缺少“(”。 所在位置 行:1 字符: 32 + if "exec(" in content or "compile(" in content: + ~~ 表达式或语句中包含意外的标记“in”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingOpenParenthesisInIfStatement PS C:\Users\Administrator\Desktop> print(f"⚠️ Potentially unsafe sitecustomize: {sitecustomize_path}") f⚠️ Potentially unsafe sitecustomize: {sitecustomize_path} : 无法将“f⚠️ Potentially unsafe sitecustomize: {sitecustomize_p ath}”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 31 + ... print(f"⚠️ Potentially unsafe sitecustomize: {sitecustomize_pat ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (f⚠️ Potentially...customize_path}:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> return False False : 无法将“False”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 32 + return False + ~~~~~ + CategoryInfo : ObjectNotFound: (False:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> except Exception as e: except : 无法将“except”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 13 + except Exception as e: + ~~~~~~ + CategoryInfo : ObjectNotFound: (except:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> print(f"⚠️ Error validating sitecustomize: {e}") f⚠️ Error validating sitecustomize: {e} : 无法将“f⚠️ Error validating sitecustomize: {e}”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名 称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 23 + print(f"⚠️ Error validating sitecustomize: {e}") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (f⚠️ Error validating sitecustomize: {e}:String) [], CommandNotFoundExce ption + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> sys.addaudithook(safe_audit_hook) safe_audit_hook : 无法将“safe_audit_hook”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 所在位置 行:1 字符: 18 + sys.addaudithook(safe_audit_hook) + ~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (safe_audit_hook:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator\Desktop> # 1. 测试基本功能 PS C:\Users\Administrator\Desktop> python -c "import sys; print(sys.version)" Error in sitecustomize; set PYTHONVERBOSE for traceback: AttributeError: module 'sys' has no attribute '_pth_handler' 3.10.10 (tags/v3.10.10:aad5f6a, Feb 7 2023, 17:20:36) [MSC v.1929 64 bit (AMD64)] PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 2. 测试.pth文件处理 PS C:\Users\Administrator\Desktop> python -c "import tempfile; t=tempfile.NamedTemporaryFile(suffix='.pth', mode='w'); t.write('test_path'); t.flush(); import site; site.addsitedir(os.path.dirname(t.name)); print('Success')" Error in sitecustomize; set PYTHONVERBOSE for traceback: AttributeError: module 'sys' has no attribute '_pth_handler' Traceback (most recent call last): File "<string>", line 1, in <module> NameError: name 'os' is not defined PS C:\Users\Administrator\Desktop> PS C:\Users\Administrator\Desktop> # 3. 测试模块导入 PS C:\Users\Administrator\Desktop> python -c "import torch, numpy as np; print(f'Torch: {torch.__version__}, Numpy: {np.__version__}')" Error in sitecustomize; set PYTHONVERBOSE for traceback: AttributeError: module 'sys' has no attribute '_pth_handler' Torch: 2.0.0+cpu, Numpy: 1.26.4 PS C:\Users\Administrator\Desktop>
最新发布
08-23
<think>我们遇到了一个关键问题:在修复后,测试环境时出现了`AttributeError: module 'sys' has no attribute '_pth_handler'`错误。这表明我们的`sitecustomize.py`试图访问`sys._pth_handler`,但该属性不存在。 问题分析: 1. 在Python的site模块中,`_pth_handler`是内部使用的,并非公开API。 2. 我们之前的修复脚本尝试替换`sys._pth_handler`,但在某些Python版本中可能不可用。 3. 此外,测试脚本中出现了编码问题(尝试打印Unicode字符时出现编码错误)。 解决方案: 1. 避免使用内部属性:不再尝试替换`_pth_handler`,而是采用更安全的方式处理.pth文件。 2. 简化sitecustomize.py:只做必要的安全检查,而不修改内部处理机制。 3. 在测试脚本中避免使用非ASCII字符,以防止输出编码问题。 具体步骤: 步骤1:修改Repair-PythonSite函数中的sitecustomize.py内容,移除对`sys._pth_handler`的修改。 步骤2:在测试脚本中,将Unicode字符替换为纯文本(例如,用[OK]代替✅)。 修改后的安全sitecustomize.py内容: ```python # SAFE SITECUSTOMIZE import sys import os def safe_pth_handler(pth_file): """Safe .pth file handler with encoding fallback""" try: with open(pth_file, 'r', encoding='utf-8') as f: content = f.read() except UnicodeDecodeError: try: with open(pth_file, 'r', encoding='latin-1') as f: content = f.read() except: return False # Basic validation if "exec" in content or "compile" in content: return False # Only allow simple path additions lines = [line.strip() for line in content.splitlines() if line.strip()] for line in lines: if line.startswith(('import', 'sys.', 'os.')): return False # Add valid paths for line in lines: if os.path.exists(line): sys.path.insert(0, line) return True # 注意:不再修改sys._pth_handler,而是直接使用我们的安全处理器 # 但是,我们如何让site模块使用我们的处理器呢? # 由于site模块内部机制,我们无法直接替换,因此我们改为在sitecustomize.py中扫描并处理.pth文件 # 我们手动处理site-packages目录下的.pth文件 # 获取site-packages目录 site_packages = [p for p in sys.path if 'site-packages' in p] for dir_path in site_packages: if os.path.isdir(dir_path): for filename in os.listdir(dir_path): if filename.endswith('.pth'): full_path = os.path.join(dir_path, filename) safe_pth_handler(full_path) # 注意:这种方法会重复添加路径,但为了修复环境,暂时这样处理 ``` 步骤3:修改测试函数Test-PythonEnvironment,避免使用Unicode字符。 修改后的测试命令: ```powershell $moduleTest = python -c @" try: import site, os, sys print('[OK] Core modules imported') # Test sitecustomize site_dir = os.path.dirname(site.__file__) sitecustomize_path = os.path.join(site_dir, 'sitecustomize.py') if os.path.exists(sitecustomize_path): print('[OK] sitecustomize.py exists: ' + sitecustomize_path) else: print('[WARN] sitecustomize.py not found') except Exception as e: print('[ERROR] ' + str(e)) "@ ``` 步骤4:在修复函数中,我们不再需要修改site.py,因为我们已经移除了对内部属性的依赖。因此,可以跳过对site.py的修改(或者保留之前的编码修复,因为那是有益的)。 注意:我们之前对site.py的编码修复是必要的,所以保留。 步骤5:重新运行修复脚本,并测试。 下面给出修改后的函数代码: 注意:由于之前已经移除了对`sys._pth_handler`的修改,现在新的sitecustomize.py采用主动扫描并处理.pth文件的方式。 完整代码调整如下:</think>### 终极问题分析与解决方案 从测试结果看,核心问题在于 `sitecustomize.py` 中尝试访问 `sys._pth_handler` 属性,但该属性在 Python 3.10 中不存在。同时,测试脚本中的 Unicode 字符(✅/❌)导致 GBK 编码错误。让我们彻底解决这些问题: ### 修复方案 ```powershell function Repair-PythonSite { param( [string]$PythonPath = "E:\Python310" ) # 1. 定位关键目录 $libPath = "$PythonPath\Lib" $sitePackages = "$PythonPath\Lib\site-packages" # 2. 彻底移除所有自定义文件 $filesToRemove = @( "$libPath\sitecustomize.py", "$libPath\sitecustomize.pyc", "$sitePackages\environment-helper.pth", "$sitePackages\environment_helper.py", "$sitePackages\distutils-precedence.pth" ) foreach ($file in $filesToRemove) { if (Test-Path $file) { Remove-Item $file -Force -ErrorAction SilentlyContinue Write-Host "🧹 Removed: $file" -ForegroundColor Yellow } } # 3. 修复原始site.py文件(保留编码修复) $sitePath = "$libPath\site.py" if (Test-Path $sitePath) { # 备份原始文件 Copy-Item $sitePath "$sitePath.bak" -Force # 修复编码问题 $content = [System.IO.File]::ReadAllText($sitePath, [System.Text.Encoding]::UTF8) $content = $content -replace "for n, line in enumerate\(f\):", @" # Fixed encoding handling try: content = f.read() except UnicodeDecodeError: f.close() f = open(fullname, encoding='utf-8') content = f.read() lines = content.splitlines() for n, line in enumerate(lines): "@ [System.IO.File]::WriteAllText($sitePath, $content, [System.Text.Encoding]::UTF8) Write-Host "🔧 Repaired site.py encoding handling" -ForegroundColor Cyan } # 4. 创建安全的sitecustomize.py(简化版) $safeSiteCustomize = @' # SAFE SITECUSTOMIZE import sys import os def safe_pth_handler(pth_file): """Safe .pth file handler with encoding fallback""" try: with open(pth_file, 'r', encoding='utf-8') as f: content = f.read() except UnicodeDecodeError: try: with open(pth_file, 'r', encoding='latin-1') as f: content = f.read() except: return False # Basic validation if "exec" in content or "compile" in content: return False # Only allow simple path additions lines = [line.strip() for line in content.splitlines() if line.strip()] for line in lines: if line.startswith(('import', 'sys.', 'os.')): return False # Add valid paths for line in lines: if os.path.exists(line): sys.path.insert(0, line) return True # 安全地注册处理器(兼容不同Python版本) if hasattr(sys, 'addaudithook'): # Python 3.8+ 使用审计钩子 def audit_hook(event, args): if event == "site.addsitedir": for pth_file in args[1]: safe_pth_handler(pth_file) sys.addaudithook(audit_hook) print("[SAFE SITE] Audit hook registered") else: # 旧版本Python使用猴子补丁 import site original_addsitedir = site.addsitedir def safe_addsitedir(sitedir, known_paths=None): if known_paths is None: known_paths = [] # 处理.pth文件 for name in os.listdir(sitedir): if name.endswith('.pth'): pth_file = os.path.join(sitedir, name) if not safe_pth_handler(pth_file): print(f"[WARNING] Skipped unsafe .pth file: {pth_file}") return original_addsitedir(sitedir, known_paths) site.addsitedir = safe_addsitedir print("[SAFE SITE] Patched addsitedir") '@ [System.IO.File]::WriteAllText("$libPath\sitecustomize.py", $safeSiteCustomize, [System.Text.Encoding]::UTF8) Write-Host "🔧 Created safe sitecustomize.py" -ForegroundColor Cyan # 5. 验证修复 Write-Host "🔄 Testing Python environment..." -ForegroundColor Cyan python -S -c "import site; print('Site module loaded successfully')" } function Test-PythonEnvironment { param( [string]$PythonPath = "E:\Python310" ) # 1. 测试基本功能(避免Unicode字符) $basicTest = python -c "import sys; print('Python version:', sys.version.split()[0])" Write-Host $basicTest # 2. 测试模块导入(纯文本输出) $moduleTest = python -c @" try: import site, os, sys print('[OK] Core modules imported') # Test sitecustomize site_dir = os.path.dirname(site.__file__) sitecustomize_path = os.path.join(site_dir, 'sitecustomize.py') if os.path.exists(sitecustomize_path): print('[OK] sitecustomize.py exists') else: print('[WARN] sitecustomize.py not found') except Exception as e: print('[ERROR]', str(e)) "@ Write-Host $moduleTest # 3. 测试.pth文件处理 $pthTest = python -c @" import tempfile import os import site try: with tempfile.NamedTemporaryFile(suffix='.pth', delete=False) as tmp: tmp.write(b'test_path\n') pth_path = tmp.name site.addsitedir(os.path.dirname(pth_path)) print('[OK] .pth file processed successfully') except Exception as e: print('[ERROR]', str(e)) finally: if os.path.exists(pth_path): os.unlink(pth_path) "@ Write-Host $pthTest } # 执行修复 Repair-PythonSite -PythonPath "E:\Python310" # 重启PowerShell会话 Write-Host "`n🔄 Please restart PowerShell session for changes to take effect" -ForegroundColor Yellow Write-Host "Close this window and open a new one" -ForegroundColor Yellow ``` ### 关键修复说明 1. **完全兼容的 sitecustomize 实现**: ```python # Python 3.8+ 使用审计钩子 if hasattr(sys, 'addaudithook'): def audit_hook(event, args): if event == "site.addsitedir": for pth_file in args[1]: safe_pth_handler(pth_file) sys.addaudithook(audit_hook) # 旧版本Python使用猴子补丁 else: import site original_addsitedir = site.addsitedir def safe_addsitedir(sitedir, known_paths=None): # 处理.pth文件 for name in os.listdir(sitedir): if name.endswith('.pth'): pth_file = os.path.join(sitedir, name) if not safe_pth_handler(pth_file): print(f"[WARNING] Skipped unsafe .pth file: {pth_file}") return original_addsitedir(sitedir, known_paths) site.addsitedir = safe_addsitedir ``` - 支持 Python 3.8+ 的审计钩子 - 兼容旧版本的猴子补丁 - 避免使用内部 `_pth_handler` 属性 2. **安全的测试脚本**: - 所有输出使用纯文本(避免 ✅/❌ 等 Unicode 字符) - 错误处理更健壮 - 完整的路径清理机制 3. **增强的错误处理**: ```python try: # 测试代码 except Exception as e: print('[ERROR]', str(e)) finally: # 清理资源 ``` ### 执行流程 1. **运行修复脚本**: ```powershell .\Repair-Script.ps1 ``` 2. **重启 PowerShell**: - 关闭当前窗口 - 打开新的 PowerShell 会话 3. **验证修复**: ```powershell # 测试基本功能 python -c "import sys; print(sys.version)" # 测试模块导入 python -c "import site, os, sys; print('Modules imported')" # 测试.pth处理 python -c "import tempfile; t=tempfile.NamedTemporaryFile(suffix='.pth'); t.write(b'test'); t.flush(); import site; site.addsitedir(os.path.dirname(t.name))" ``` ### 补充安全措施 添加环境变量解决 Windows 控制台编码问题: ```powershell # 设置控制台编码为UTF-8 [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $env:PYTHONUTF8 = 1 $env:PYTHONIOENCODING = "utf-8" ``` 在 PowerShell 配置文件中添加(`$PROFILE`): ```powershell # 永久解决编码问题 if ($env:OS -like "*Windows*") { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $env:PYTHONUTF8 = 1 $env:PYTHONIOENCODING = "utf-8" } ``` ### 完整修复后验证 ```powershell # 在新会话中测试 Test-PythonEnvironment -PythonPath "E:\Python310" # 预期输出 Python version: 3.10.10 [OK] Core modules imported [OK] sitecustomize.py exists [OK] .pth file processed successfully ``` 这个终极解决方案解决了: 1. `sys._pth_handler` 属性不存在的问题 2. Unicode 字符导致的 GBK 编码错误 3. 不同 Python 版本的兼容性问题 4. 测试脚本的健壮性问题
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值