简体   繁体   English

通过电子邮件发送 python 中未修改的打印语句的内容

[英]Send the contents from unmodified print statement by e-mail in python

I have a script that runs main() and at the end I want to send the contents it has by e-mail.我有一个运行main()的脚本,最后我想通过电子邮件发送它的内容。 I don't want to write new files nor anything.我不想写新文件也不想写任何东西。 Just have the original script be unmodified and at the end just send the contents of what it printed.只需不修改原始脚本,最后只需发送打印的内容即可。 Ideal code:理想代码:

main()
send_mail()

I tried this:我试过这个:


def main():
  print('HELLOWORLD')

def send_email(subject='subject', message='', destination='me@gmail.com', password_path=None):
    from socket import gethostname
    from email.message import EmailMessage
    import smtplib
    import json
    import sys

    server = smtplib.SMTP('smtp.gmail.com', 587)
    smtplib.stdout = sys.stdout # <<<<<-------- why doesn't it work?
    server.starttls()
    with open(password_path) as f:
        config = json.load(f)
        server.login('me@gmail.com', config['password'])

        # craft message
        msg = EmailMessage()

        #msg.set_content(message)
        msg['Subject'] = subject
        msg['From'] = 'me@gmail.com'
        msg['To'] = destination
        # send msg
        server.send_message(msg)

if __name__ == '__main__':
    main()
    send_mail()

but it doesn't work.但它不起作用。

I don't want to write other files or change the original python print statements.我不想写其他文件或更改原来的 python 打印语句。 How to do this?这个怎么做?


I tried this:我试过这个:

def get_stdout():
    import sys

    print('a')
    print('b')
    print('c')

    repr(sys.stdout)

    contents = ""
    #with open('some_file.txt') as f:
    #with open(sys.stdout) as f:
    for line in sys.stdout.readlines():
        contents += line
    print(contents)

but it does not let me read sys.stdout because it says its not readable.但它不允许我阅读sys.stdout因为它说它不可读。 How can I open it in readable or change it to readable in the first place?如何首先以可读方式打开它或将其更改为可读?


I checked all of the following links but none helped:我检查了以下所有链接,但没有任何帮助:

To send e-mails I am using:要发送电子邮件,我正在使用:

def send_email(subject, message, destination, password_path=None):
    from socket import gethostname
    from email.message import EmailMessage
    import smtplib
    import json

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    with open(password_path) as f:
        config = json.load(f)
        server.login('me123@gmail.com', config['password'])
        # craft message
        msg = EmailMessage()

        message = f'{message}\nSend from Hostname: {gethostname()}'
        msg.set_content(message)
        msg['Subject'] = subject
        msg['From'] = 'me123@gmail.com'
        msg['To'] = destination
        # send msg
        server.send_message(msg)

note I have my password in a json file using an app password as suggested by this answer https://stackoverflow.com/a/60996409/3167448 .请注意,我的密码在 json 文件中,使用了此答案https://stackoverflow.com/a/60996409/3167448建议的应用程序密码。

using this to collect the contents from stdout by writing it to a custom stdout file using the builtin function print:通过使用内置 function 打印将其写入自定义标准输出文件,使用它从标准输出收集内容:

import sys 
from pathlib import Path
def my_print(*args, filepath='~/my_stdout.txt'):
    filepath = Path(filepath).expanduser()
    # do normal print
    __builtins__['print'](*args, file=sys.__stdout__) #prints to terminal
    # open my stdout file in update mode
    with open(filepath, "a+") as f:
        # save the content we are trying to print
        __builtins__['print'](*args, file=f) #saves in a file

def collect_content_from_file(filepath):
    filepath = Path(filepath).expanduser()
    contents = ''
    with open(filepath,'r') as f:
        for line in f.readlines():
            contents = contents + line
    return contents

Note the a+ to be able to create the file if it already does NOT exist.如果文件不存在,请注意a+以便能够创建文件。

Note that if you want to delete the old contents of your custom my_stdout.txt you need to delete the file and check if it exists:请注意,如果要删除自定义my_stdout.txt的旧内容,则需要删除该文件并检查它是否存在:

    # remove my stdout if it exists
    os.remove(Path('~/my_stdout.txt').expanduser()) if os.path.isfile(Path('~/my_stdout.txt').expanduser()) else None

The credits for the print code are from the answer here: How does one make an already opened file readable (eg sys.stdout)?打印代码的功劳来自这里的答案: 如何使已打开的文件可读(例如 sys.stdout)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM