【问题标题】:Adapting script to read from text file调整脚本以从文本文件中读取
【发布时间】:2012-01-09 00:25:10
【问题描述】:

我需要调整以下脚本以从文件中读取,特别是我需要提取“域”和“预期响应”。目前它们是在代码中手动编写的,因为我不够熟练,无法更有效地重构它。

#!/usr/bin/python
import dns.resolver
from smtplib import SMTP
import datetime

debuglevel = 0

domain = 'exampledomain.co.uk'
expected_responses = ['example.co.uk.', 'example2.co.uk.']
for x in dns.resolver.query(domain, 'MX'):
        if x.to_text().split()[1] not in expected_responses:
                print "Unexpected MX record found!"
                smtp = SMTP()
                smtp.set_debuglevel(debuglevel)
                smtp.connect('localhost', 25)

                from_addr = "MX ERROR <MXERROR@example.net>"
                to_addr = "example@example.com"

                subj = "MX ERROR"
                date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )

                message_text = "Dearest colleagues\nSomething appears to be wrong with the MX records for example.co.uk\n\nDON'T PANIC!\n"

                msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text )


                smtp.sendmail(from_addr, to_addr, msg)
                smtp.quit()
        else:
                print x.to_text().split()[1] + " example.uk MX records OK!"

我的第一个想法是使用 .txt 文件,但我不知道如何根据我的 python 知识从同一个文件中区分域和预期响应。我搜索并阅读了 import csv 函数,这似乎是最好的选择,但我没有任何使用经验。

谁能提供我如何将 import csv 应用于我的代码的示例?

问候

克里斯

【问题讨论】:

标签: python csv


【解决方案1】:

http://docs.python.org/library/configparser.html

这可能是您正在寻找的更多内容。使用 *.ini 文件似乎是配置文件的标准做法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2019-08-03
    • 2014-03-29
    • 1970-01-01
    相关资源
    最近更新 更多