[英]Send the contents from unmodified print statement by e-mail in python
我有一個運行main()
的腳本,最后我想通過電子郵件發送它的內容。 我不想寫新文件也不想寫任何東西。 只需不修改原始腳本,最后只需發送打印的內容即可。 理想代碼:
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 打印語句。 這個怎么做?
我試過這個:
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
因為它說它不可讀。 如何首先以可讀方式打開它或將其更改為可讀?
我檢查了以下所有鏈接,但沒有任何幫助:
要發送電子郵件,我正在使用:
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建議的應用程序密碼。
通過使用內置 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
如果文件不存在,請注意a+
以便能夠創建文件。
請注意,如果要刪除自定義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
打印代碼的功勞來自這里的答案: 如何使已打開的文件可讀(例如 sys.stdout)?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.