环境python脚本,需要使用以前运行的结果

2024-09-30 20:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我相信有很多方法可以做到这一点,但我之所以这么问是因为我不知道从哪里开始寻找一种方法。我有一个python脚本,它运行一些基本的bash命令,并根据输出将电子邮件发送到给定的电子邮件地址。我想让它这样一个电子邮件将只发送,如果信息与脚本的最后输出不同。在

所以假设我运行了一个'lpstat-p'并且它发送了一个电子邮件,因为打印机'a'被禁用,cron在一个小时后再次运行脚本我只希望在'a'之外的东西需要电子邮件通知时再发送一封电子邮件。在

我可能已经讲得太详细了,但实际上我只想让脚本知道在脚本的前几次运行中发生了什么-这有什么意义吗?我知道我可以在一个文件上运行“touch”,但这看起来相当原始,所以我想知道python是否有一个很好的内置方法来处理这个问题,而不会变得过于复杂。在

这里有一个简单的例子,说明如果我的解释没有道理,我会怎么做。在

# The string used to find disabled pritners based on the stdout of lpstat
string_check = 'disabled'
stdout = commands.getoutput( 'lpstat -p' )
lpout  = stdout.split( '\n' )
disabled = []

# Cycle through the output of lpstat which has been split into tokens based on each line of the output and save the lines that have a substring match with string_check
for line in lpout:
    if string_check in line:
        disabled.append( line )

# Initiate the required variables for constructing a basic email
new_message = ""
SERVER = ""
FROM = ""
TO = ""
SUBJECT = ""
TEXT = ""
message = ""

# Just some string manipulation - tries to remove useless, redundant information from the lpstat output
for line in disabled:
    line = line.replace( "printer ", "" )
    line = line.replace( " is ", "" )
    line = line.replace( "idle.", "\t" )
    line = line.replace( string_check, "\t" )
    new_message += "\t" + line + "\n"

SERVER = "localhost"

FROM = "email"
TO = "email"
SUBJECT = "Printer unnexpectedly disabled"
TEXT = new_message

# Email template
message = """\
From: %s
To: %s
Subject: %s

Printers that seem to be disabled:

%s
""" % ( FROM, TO, SUBJECT, TEXT )

# if there ended up being some stuff in the disabled array then send the email
if len( disabled ) > 0:
    server = smtplib.SMTP( SERVER )
    server.sendmail ( FROM, TO, message )
    server.quit( )

Tags: theto方法infrom脚本messagestring
2条回答

shelve模块在Python中提供了一个非常简单的持久字典。在

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

我建议您直接使用Pickle或JSON,您可以获得比shelve更多的灵活性。请注意,这段代码与Pickle、JSON或Yaml的工作原理几乎相同。在

基本上,你会在跑步结束时写出你想要的对象:

json.dump(disabled, open('disabled_list.json', 'wb'))

然后在下一次运行开始时,您将加载该json对象,并根据之前不存在的对象筛选新行:

^{pr2}$

相关问题 更多 >