VS Code中msgraph.core导入无法解析问题排查(OneDrive查重场景)
问题描述
我在Windows 11系统的VS Code里使用Python 3.11(未使用conda环境)编写代码,用于检查OneDrive家庭版中的重复文件。已通过pip安装msgraph-core 1.0.0,但Pylance始终提示Import "msgraph.core" could not be resolved。我在Graph Explorer中已授权并能执行简单查询,目前暂未配置Azure客户端ID,疑惑为何会出现该导入无法解析的错误。
相关代码:
from msgraph.core import GraphClient from azure.identity import InteractiveBrowserCredential import hashlib # Azure app registration details CLIENT_ID = 'YOUR_CLIENT_ID' # Replace with your Azure AD client ID # Scopes required by the app SCOPES = ['Files.ReadWrite.All'] # Scope for OneDrive access # Authentication with Interactive Browser Credential credential = InteractiveBrowserCredential(client_id=CLIENT_ID) graph_client = GraphClient(credential=credential, scopes=SCOPES) # Create an empty dictionary to store the hashes and file names hashes = {} # Function to process files and find duplicates in a folder def process_files(folder_id): request_url = f'me/drive/items/{folder_id}/children' drive_items = graph_client.get(request_url).json() for item in drive_items['value']: # Check if the item is a file if 'file' in item: # Get the file content file_content = graph_client.get(item['@microsoft.graph.downloadUrl']).content # Create a hash object using md5 hash_obj = hashlib.md5() hash_obj.update(file_content) hash_digest = hash_obj.hexdigest() if hash_digest in hashes: print(f"{item['name']} is a duplicate of {hashes[hash_digest]}") else: hashes[hash_digest] = item['name'] elif 'folder' in item: # If the item is a folder, process its contents process_files(item['id']) # Start processing from the root folder root_folder = graph_client.get('me/drive/root').json() process_files(root_folder['id'])
解决方案
确认VS Code使用的Python解释器匹配
按Ctrl+Shift+P打开命令面板,输入Python: Select Interpreter,选择你安装了msgraph-core的Python 3.11环境。可在终端执行pip show msgraph-core,查看输出的Location路径,确认该路径对应的解释器被选中。刷新Pylance缓存
按Ctrl+Shift+P输入Developer: Reload Window重启VS Code窗口,让Pylance重新扫描已安装包。若仍未解决,可在VS Code设置中搜索python.analysis.extraPaths,添加msgraph-core的安装路径(即pip show msgraph-core输出的Location值)。验证pip安装状态
在VS Code终端(确保使用选中的解释器)执行pip list,确认msgraph-core 1.0.0在列表中。若未找到,重新执行pip install msgraph-core==1.0.0,确保安装无报错。关于Azure客户端ID的说明
未配置客户端ID的问题与当前导入错误无关,该错误是本地环境的包识别问题,和Graph API授权逻辑不相关。导入问题解决后,需前往Azure门户注册应用获取CLIENT_ID才能正常运行代码。
内容的提问来源于stack exchange,提问作者user1913949

