计时器函数到Python脚本

时间:2018-08-13 16:15:42

标签: python timer

我是Python的新手,我想弄清楚如何在脚本中设置计时器,使其每天在特定时间运行,而不是使用Windows Task Scheduler。

下面的脚本打开一个启用宏的excel电子表格并运行该宏。我已确认一切正常。

#REFERENCE FILE PATH AND RUN MACROS#
import os
import win32com
import win32com.client

# path where macro enable sheet is
if os.path.exists ("C:\\Users\\hernri01\\Documents\\Python Scripts\\SDK Cert 
Source\\Macro Autosave\\Macro_SDKtoXLSX.xlsm"):
    xl = win32com.client.Dispatch('Excel.Application')
    xl.Workbooks.Open(Filename = "C:\\Users\\hernri01\\Documents\\Python 
    Scripts\\SDK Cert Source\\Macro Autosave\\Macro_SDKtoXLSX.xlsm", 
    ReadOnly=1)

    # runs macro
    xl.Application.Run("openfilesandsave")
    del xl

#PRINT FINAL COMPLETED MESSAGE
print("Macro refresh completed!")

当我尝试添加计时器时,我收到一条错误消息。下面的脚本和错误:

#REFERENCE FILE PATH AND RUN MACROS#
import os
import win32com
import win32com.client
import datetime
from threading import Timer

xl = win32com.client.Dispatch('Excel.Application')
def run_prog():
    xl.Workbooks.Open(Filename = "C:\\Users\\hernri01\\Documents\\Python 
    Scripts\\SDK Cert Source\\Macro Autosave\\Macro_SDKtoXLSX.xlsm", 
    ReadOnly=1)
    xl.Application.Run("openfilesandsave")
    xl.Workbooks.Close()

    #PRINT FINAL COMPLETED MESSAGE#
    print("Macro refresh completed!")

    # how often python to run
    #t = Timer(3600 * 24,run_prog) #3600 = seconds in 1 hour
    t = Timer(10,run_prog) # 10 = run every 10 seconds
    t.start()

x=datetime.datetime.today()
#y=x.replace(day=x.day, hour=4, minute=0, second=0, microsecond=0)
y=x.replace(day=x.day, hour=11, minute=56, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
print (secs)

t = Timer(secs, run_prog)
t.start()

print("Macro refresh completed!")

错误消息:

48
Macro refresh completed!
>>> Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\hernri01\AppData\Local\Programs\Python\Python37- 
32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\hernri01\AppData\Local\Programs\Python\Python37- 
32\lib\threading.py", line 1158, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\hernri01\Documents\Python Scripts\SDK Cert Source\Macro 
Autosave\openFileSave.py", line 14, in run_prog

谢谢您的帮助。

0 个答案:

没有答案