每2小时自动运行python脚本并生成csv文件



所以,我有一个像这样的python代码,

from arcgis.features import SpatialDataFrame
fl = known_item.tables[0]
# Use the `from_layer` method of the Spatial DataFrame to create a new Spatial DataFrame
sdf = SpatialDataFrame.from_layer(fl)
df = sdf.copy()
df = df[df["site_status"]!="Closed"]
print(len(df))
df.head()
## save the file to local directory
df.to_csv(path+'Status.csv')

正如您所看到的,该代码输出一个csv文件。我将csv文件保存到本地目录中。我只想每2小时自动运行一次代码,并生成一个新的csv文件。因此,每隔2小时,新的csv文件就会覆盖旧的csv。

我对自动化知识不多,所以任何形式的帮助都将不胜感激。

谢谢。

您可以睡眠2小时,并将整个代码放入for循环中

import time
from arcgis.features import SpatialDataFrame
for i in range(100):
fl = known_item.tables[0]
# Use the `from_layer` method of the Spatial DataFrame to create a new Spatial DataFrame
sdf = SpatialDataFrame.from_layer(fl)
df = sdf.copy()
df = df[df["site_status"]!="Closed"]
print(len(df))
df.head()
## save the file to local directory
df.to_csv(path+'Status.csv')
time.sleep(60*60*2)#60 seconds*60 minutes*2 = 2 hours

好吧,有一种简单的方法可以实现这一点!您可以将代码封装在while循环中,并在循环体的末尾添加time.sleep((函数。

from arcgis.features import SpatialDataFrame
import time
while True:
fl = known_item.tables[0]
# Use the `from_layer` method of the Spatial DataFrame to create a new Spatial DataFrame
sdf = SpatialDataFrame.from_layer(fl)
df = sdf.copy()
df = df[df["site_status"]!="Closed"]
print(len(df))
df.head()
## save the file to local directory
df.to_csv(path+'Status.csv')

# wait for 2 hours
time.sleep(7200) 

最新更新