通过python中的电子邮件发送未修改的打印语句中的内容 [英] Send the contents from unmodified print statement by e-mail in python
问题描述
我有一个运行 main()
的脚本,最后我想通过电子邮件发送它包含的内容。我不想写任何新文件。只需将原始脚本进行修改,最后只发送其打印内容即可。理想代码:
I have a script that runs main()
and at the end I want to send the contents it has by e-mail. 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()
我尝试过此操作:
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()
但它不起作用。
我不想编写其他文件或更改原始的python打印语句。
I don't want to write other files or change the original python print statements. How to do 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)
但它不允许我阅读 sys.stdout
,因为它说不可读的。我该如何以可读的方式打开它或将其更改为可读的?
but it does not let me read sys.stdout
because it says its not readable. 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:
- 如何将python脚本的输出发送到电子邮件地址
- https:// www .quora.com /如何从Python脚本发送输出到电子邮件地址
- https://bytes.com/topic/python/answers/165835-email -module-redirecting-stdout
- 将stdout重定向到Python中的文件吗?
- 如何很好地处理`open(...)`和`sys.stdout`? a>
- 从脚本中捕获标准输出吗?
- How to send output from a python script to an email address
- https://www.quora.com/How-can-I-send-an-output-from-a-Python-script-to-an-email-address
- https://bytes.com/topic/python/answers/165835-email-module-redirecting-stdout
- Redirect stdout to a file in Python?
- How to handle both `with open(...)` and `sys.stdout` nicely?
- Capture stdout from a script?
推荐答案
要发送电子邮件,我正在使用:
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)
请注意,我使用应用程序将密码保存在json文件中此答案建议的密码 https://stackoverflow.com/a/60996409/3167448 。
note I have my password in a json file using an app password as suggested by this answer https://stackoverflow.com/a/60996409/3167448.
使用此函数通过使用内置函数print将其写入自定义stdout文件来从stdout收集内容:
using this to collect the contents from stdout by writing it to a custom stdout file using the builtin function print:
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
请注意 a +
可以创建文件(如果尚不存在)。
Note the a+
to be able to create the file if it already does NOT exist.
请注意,如果要删除自定义 my_stdout.txt
的旧内容,则需要删除文件并检查是否存在:
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:
# remove my stdout if it exists
os.remove(Path('~/my_stdout.txt').expanduser()) if os.path.isfile(Path('~/my_stdout.txt').expanduser()) else None
打印代码的信用来自此处的答案:如何使已打开的文件可读(例如sys.stdout)?
The credits for the print code are from the answer here: How does one make an already opened file readable (e.g. sys.stdout)?
这篇关于通过python中的电子邮件发送未修改的打印语句中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!