好吧,我确信可能有很多方法可以做到这一点,但我问,因为我不知道从哪里开始寻找一种方法来做到这一点.我有一个python脚本运行一些基本的bash命令,并根据输出将发送电子邮件到给定的电子邮件地址.我想这样做,只有当该信息与脚本的最后输出不同时才会发送电子邮件.
所以说我运行'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( )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |