在 Python 中更新 OneDrive 文件夹

问题描述 投票:0回答:1

我正在开发一个程序,该程序使用存储在 Excel 文件中的时间表来打开和关闭某些内容。该程序在后台运行,每分钟检查一次 Excel 数据。该文件存储在 OneDrive 上,该 OneDrive 映射到运行程序的计算机上的本地磁盘。

我可以使用 pandas 访问该文件,没有任何问题:

data = pd.read_excel(r"C:\Users\Ryszard\OneDrive - Politechnika Warszawska\Rezerwacje systemu HIL\HIL - schedule.xlsx", sheet_name=f'{month}')

但是,我面临同步问题。当我在脚本运行之前手动打开文件时,它会正确更新。但如果我尝试直接通过脚本访问它,它似乎不会刷新数据。这意味着 pandas 函数 read_excel 似乎不会像手动打开文件那样触发 OneDrive 同步。

有没有办法在使用 pandas 访问文件之前强制更新文件?您有什么想法如何处理吗?我考虑过使用 PowerShell 命令,但没有找到任何有效的方法。我没有使用 OneDrive API,也不想使用,因为对于这种情况来说,它似乎没有必要并且过于复杂。

python pandas onedrive
1个回答
0
投票

根据超级用户站点的此问题和答案,您可以关闭 OneDrive 进程,然后重新启动后台任务以强制重新同步。

要在Python中执行此操作,我们需要找到OneDrive.exe文件,然后发送两个命令,然后等待并最终加载文件。

import subprocess
import winreg
import pandas as pd
from time import sleep


# pull the location of your OneDrive.exe file from the registry
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\OneDrive',
                     0, winreg.KEY_READ)
onedrive_exe, _ = winreg.QueryValueEx(key, 'OneDriveTrigger')
key.Close()

# turn off OneDrive then restart it as a background task. 
# Use Popen to avoid hanging since OneDrive is a continuous process
subprocess.run([onedrive_exe, '/shutdown'])
subprocess.Popen([onedrive_exe, '/background'])

# wait a short period, then load the dataframe
sleep(5)
data = pd.read_excel(r"C:\Users\Ryszard\OneDrive - Politechnika Warszawska\Rezerwacje systemu HIL\HIL - schedule.xlsx", sheet_name=f'{month}')
© www.soinside.com 2019 - 2024. All rights reserved.