Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
每2小时自动运行python脚本并生成csv文件_Python_Csv_Automation - Fatal编程技术网

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

每2小时自动运行python脚本并生成csv文件,python,csv,automation,Python,Csv,Automation,我有一个类似这样的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["

我有一个类似这样的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文件

我对自动化没有太多的了解,所以任何帮助都将不胜感激


谢谢。

好吧,有一个简单的方法可以做到这一点!您可以将代码包装在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) 

你可以睡两个小时,然后把整个代码放在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

您可能正在寻找Cron/cronjob抱歉忘了提及,我没有访问Cron的权限。谢谢您的回答。我每隔5分钟测试一次。它第一次运行代码并将csv文件放入目录中,但在5分钟后不会执行任何操作。我必须安排它每2小时运行一次吗?嗨,我看到你已经接受了另一个答案。无论如何,我的代码应该无限循环,直到你结束程序。我不知道为什么5分钟后它什么也没做。也许你把5分钟的间隔时间设置错了?是我的错。你的回答也是正确的。我的csv文件已打开,因此无法更新新文件。我刚想出来。非常感谢,非常感谢。您的代码正常工作,每2小时更新一次csv文件。你能告诉我你为什么用i在100范围内吗?谢谢。看,这是一个for循环,它将运行(100)次,但是你可以增加这个数字或将for循环设置为True:这样它就可以无限运行