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

标签 python scripting

好吧,我敢肯定可能有很多方法可以做到这一点,但我问是因为我不知道从哪里开始寻找一种方法来做到这一点。我有一个运行一些基本 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

关于python - 环境 python 脚本,需要使用以前运行的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4926147/

相关文章:

python - cx_Oracle 忽略 order by 子句

python - pyspark 和 HDFS 命令

python - 如何在 matplotlib 中将圆圈放入正确的子图中?

scripting - FFMPEG 脚本将文件夹中的所有 Webm 文件转换为 Gif,然后删除那些 Webm

linux - Linux 的自动执行脚本?

python - 从 Python 通过 COM 访问 Enterprise Architect 的特定实例

bash - 使用 bash mangles 文件从 CSV 映射重命名文件

python - Dask 数据帧如何处理大于内存的数据集?

javascript - Python 和 JavaScript 之间的连接

scripting - 使用应用程序自动执行重复任务的最佳自动化或脚本工具是什么?