for x in y loop capture instance value

时间:2017-10-31 17:31:36

标签: python python-2.7

如果我有如下字符串:

output = '''
Certificate 1:
  Valid from: Mon Jun 12 14:58:50 EDT 2017
  Valid until: Wed Jun 12 15:28:50 EDT 2019

Certificate 2:
  Valid from: Mon Jun 12 15:00:43 EDT 2017
  Valid until: Wed Jun 12 15:30:43 EDT 2019
'''

我希望在转换为unixtime时区分这两个值。如何在证书1或证书2时告诉它?

这是我到目前为止所做的工作,以获取两个日期,但我不知道该怎么说,如果这是第一个结果,那么它是证书1。

        for line in output.splitlines():
            if 'Valid until' in line:
                environment = '???'
                valid_until_time = (line.split(':', 1)[1]).strip()[4:]
                valid_until_time = valid_until_time.replace(' EDT', '')
                unixtime = time.mktime(datetime.strptime(valid_until_time, '%b %d %H:%M:%S %Y').timetuple())
                send_to_zabbixsender(zabbix_executable,
                                     zabbix_config,
                                     item_key='{0}.expirydate'.format(environment),
                                     item_value=unixtime)

3 个答案:

答案 0 :(得分:2)

只需将当前证书存储为您遇到的状态:

import time
from datetime import datetime

output = '''
Certificate 1:
  Valid from: Mon Jun 12 14:58:50 EDT 2017
  Valid until: Wed Jun 12 15:28:50 EDT 2019

Certificate 2:
  Valid from: Mon Jun 12 15:00:43 EDT 2017
  Valid until: Wed Jun 12 15:30:43 EDT 2019
'''

current_certificate = 0
for line in output.splitlines():
    if line.startswith("Certificate"):
        current_certificate = int(line.split()[1].rstrip(":"))
    if 'Valid until' in line:
        environment = '???'
        valid_until_time = (line.split(':', 1)[1]).strip()[4:]
        valid_until_time = valid_until_time.replace(' EDT', '')
        unixtime = time.mktime(datetime.strptime(valid_until_time, '%b %d %H:%M:%S %Y').timetuple())
        print("{}: {}".format(current_certificate,unixtime))

这个独立的例子打印:

1: 1560346130.0
2: 1560346243.0

答案 1 :(得分:1)

有很多不同的方法来解决这个问题。

一种方法是简单地检查它是否为证书1或2

project.assets.json

然后继续使用其余代码,只需根据需要检查 for line in output.splitlines(): if 'Certificate 1' in line: cert1Bool = True if 'Certificate 2' in line: cert1Bool = False

答案 2 :(得分:0)

我只会跟踪for循环之外的当前证书。 e.g:

    certificate = ''
    for line in output.splitlines():
        if 'certificate' in line:
            certificate = line
        else if 'Valid until' in line:
            environment = certificate
            valid_until_time = (line.split(':', 1)[1]).strip()[4:]
            valid_until_time = valid_until_time.replace(' EDT', '')
            unixtime = time.mktime(datetime.strptime(valid_until_time, '%b %d %H:%M:%S %Y').timetuple())
            send_to_zabbixsender(zabbix_executable,
                                 zabbix_config,
                                 item_key='{0}.expirydate'.format(environment),
                                 item_value=unixtime)