Skip to main content
 首页 » 编程设计

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

2025年05月04日17EasonJim

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

假设我运行了一个“lpstat -p”,它发送了一封电子邮件,因为打印机“a”被禁用,并且 cron 在一小时后再次运行该脚本我只希望在“a”以外的其他内容需要电子邮件时发送另一封电子邮件通知。

我可能说得太详细了,但实际上我只是想要一种方法让脚本知道在之前的脚本运行中发生了什么——这有意义吗?我知道我可以对文件运行“触摸”,但这看起来相当原始,所以我想知道 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( ) 

请您参考如下方法:

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

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