【问题标题】:Pass Bash Script Argument to Python Email Script将 Bash 脚本参数传递给 Python 电子邮件脚本
【发布时间】:2014-03-01 05:39:09
【问题描述】:

我有一个 Python 通知脚本,它在终端上接收一个电子邮件地址和一个命令,并发送带有标准错误和标准输出的电子邮件。在调用此 Python 脚本的 bash 脚本中,我运行了一些其他命令并制作了一些日志文件...

我想编辑 Python 脚本以允许另一个位置参数,以便我可以附加 bash 脚本在前面的步骤中创建的日志文件。这是创建附件的 Python sn-p:

def make_attachment(filename, content):
    attachment = MIMEBase('application', 'octet-stream')
    attachment.set_payload(content)
    Encoders.encode_base64(attachment)
    attachment.add_header('Content-Disposition', 'attachment; filename="'+filename+'"')
    return attachment

以及附加它的sn-p:

msg.attach(make_attachment('result.log', filename))

对于if __name__ == '__main__': 电话,我正在使用:

email_result(args.cmd.split(), args.email, args.log)

我应该注意,当我不使用 msg.attach(make_attachment('result.log', filename)) 位时,这些脚本已经可以协同工作。

当我运行 bash 脚本时,我得到了这个回溯:

Traceback (most recent call last):
    File "/home/user/scripts/notify.py", line 85, in <module>
        email_result(args.cmd.split(), args.email, args.log)
    File "/home/user/scripts/notify.py", line 66, in email_result
        msg.attach(make_attachment('result.log', filename))
    File "/home/user/scripts/notify.py", line 49, in make_attachment
        Encoders.encode_base64(attachment)
    File "/usr/lib/python2.7/email/encoders.py", line 45, in encode_base64
        encdata = _bencode(orig)
    File "/usr/lib/python2.7/email/encoders.py", line 31, in _bencode
        hasnewline = (s[-1] == '\n')
TypeError: 'file' object has no attribute '__getitem__'

我想我可能不得不使用 bash 技巧 $@,但我不知道该怎么做。

【问题讨论】:

    标签: python bash arguments


    【解决方案1】:

    result.log 文件是否在每次执行时都有内容?这可能是因为 result.log 是空的吗?

    【讨论】:

    • 好问题...几件事。我在其他地方运行了这个通知脚本,即使附件是空的,它们也会通过电子邮件发送。它们只是空文件。另外,该文件是在 bash 脚本中创建的,它只包含命令的输出(如果运行,它总是会向终端返回一些内容)。所以是的,它应该总是包含一些东西并且不应该是空的。
    • 您是否已经通过在方法中打印文件名和内容进行了调试?
    猜你喜欢
    • 2012-12-29
    • 2015-05-13
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多