首页 > 解决方案 > 如何在python中存储下一个周期的迭代值

问题描述

我计划在 servicenow 中自动分配事件。这工作正常。但是,每当下一次迭代再次运行它时,都会使用我提供的第一个employeeid 进行说明。但我想将员工详细信息存储在上次迭代中完成的位置。这是我的工作代码

# cat working_inc.py
#!/usr/bin/python

import requests, json, csv
import sys, ast
login=(userid,"password")
#open_incidents_url="URL to connect"
open_incidents_url="URL to connect"
response=requests.get(open_incidents_url,auth=login)
response=response.json()['result']
print(response)
employee_number=["empid1","empid2", "empid3","empid4"]
j=0
if len(response) < 1 :
    print("No New Tickets in OPENSHIFT / OSFI - SPT Servicenow group")
else:
    for i in response:
        print (i["number"])
        body = {"assigned_to":employee_number[j],"number": i["number"]}
        o=requests.post("https://optum.service-now.com/api/now/import/u_incident",auth=login,data=json.dumps(body))
        print(o.status_code)
        if j == 3:
            j=0
        else:
            j=j+1

在我的代码中,第一次运行时假设它将 3 inc 分配给 3 empid,但是当我下次再次运行时,它将从第一个员工开始,但我想从第 4 个 empid 开始

标签: pythonpython-3.xlistpython-2.7python-requests

解决方案


如果要在迭代之间存储数据,则必须将其保存在某个位置。您的程序每次都从 0 开始。

# cat working_inc.py
#!/usr/bin/python

import requests, json, csv
import sys, ast
login=(userid,"password")
#open_incidents_url="URL to connect"
open_incidents_url="URL to connect"
response=requests.get(open_incidents_url,auth=login)
response=response.json()['result']
print(response)
employee_id_fn = 'last_id.txt'
if not os.path.exists(employee_id_fn):
  j = 0
else:
  with open(employee_id_fn, "r") as stream:
     j = int(stream.read())

employee_number=["empid1","empid2", "empid3","empid4"]

if len(response) < 1 :
    print("No New Tickets in OPENSHIFT / OSFI - SPT Servicenow group")
else:
    for i in response:
        print (i["number"])
        body = {"assigned_to":employee_number[j],"number": i["number"]}
        o=requests.post("https://optum.service-now.com/api/now/import/u_incident",auth=login,data=json.dumps(body))
        print(o.status_code)
        j = (j + 1) % 4
    with open(employee_id_fn, "w") as stream:
       stream.write(str(j))

推荐阅读