如何将脚本结果提取到python中的一个变量中



我是这个庞大编程世界的新手,目前正在学习python。我最近创建了一个脚本,用于查询数据库并处理接收到的数据。我正试图找到一种方法,从脚本本身发送带有此脚本结果的电子邮件。我毫不怀疑如何使用电子邮件模块,但我不知道如何获得脚本的全部结果并将其放入电子邮件正文中。有人知道怎么做吗?我已经花了几个小时搜索了,不幸的是,我找到的唯一方法是保存.txt文件。但是,我不想用文件填充服务器。

我的代码:

import psycopg2 ### postgres connect module
from psycopg2 import Error
try:
connection = psycopg2.connect(user="user",
password="password",
host="host",
port="port",
database="database")
cursor = connection.cursor()
cursor.execute('''select data to retrieve as tuples.''')
bases = cursor.fetchall()
print('=-'*5,'33[31mData from query33[0m','=-'*5)
for row in bases:
print('Data1 =', row[0],'|','Data2 =', row[1])
except (Exception, Error) as error:
print("Conection with database Error", error)

基本上,重复循环会给我带来一个分为两列的数据列表,我需要在其中的电子邮件正文中发送该列表。

欢迎来到"巨大的";编程世界:(

在我开始之前,我想建议您使用stackoverflow编辑器中的代码片段来突出显示您的代码,这样更容易阅读。

您说要将脚本的输出存储到一个变量中。在python中,如果您正在运行代码,通常需要防止在脚本中运行脚本,因为脚本是独立运行的(而不是依赖于其他脚本(。我建议您将要存储的代码重写为python函数,即

def get_data_as_strings():
connection = psycopg2.connect(user="user",
password="password",
host="host",
port="port",
database="database")
cursor = connection.cursor()
cursor.execute('''select data to retrieve as tuples.''')
bases = cursor.fetchall()
#  Return the data as a string for each row (as you did before).
return [f'Data1 = {row[0]} | Data2 = {row[1]}' for row in bases]
def send_email():
try:
# Get the data as a list of strings
data = get_data_as_strings()
# Concatenate all data with newlines in between
data_str = data.join('n')
# Not sure which email module you use, but send the message here
email_module.send(data_str)  
except (Exception, Error) as error:
print("Conection with database Error", error)
if __name__ == '__main__':
send_email()

当然,你会希望它更复杂,这只是一个例子,你提到你已经有了电子邮件逻辑。这样,即使将get_data_as_strings函数存储在另一个文件中,也可以导入它并从python脚本中调用if。

我希望这能有所帮助,如果还有什么不清楚/不完整的地方,请告诉我。

您可以使用字符串格式。

message = f'{first_variable} some text between. {second_variable} some text between. {third_variable}'

如果你想将变量与消息字符串合并,你可以这样做:

var1=";客户姓氏";var2=";客户名字";

消息=";这里的静态字符串{}static again{}";。格式(var1,var2(

就像这样:(没有打印结果。如果以后需要,您应该将打印的数据保存在变量中(

# save what you want to print in a variable first
first_string = "Something here"
second_string = "More data here"
third_string = "and the last one here"
print(first_string)
print(second_string)
print(third_string)
# now you can put it in your message
message = first_string + ", " + second_string + ", " + third_string

如果我理解正确,您希望发送一封与您在控制台中打印的内容完全相同的电子邮件。是这样吗?如果是这样,那么这将有所帮助(这是你的for循环(

# idealy you want this in the same for loop that you run for printing it out in the console.
# n is a line break so "123n456" is the same as the following:
# 123
# 456

message = 'This is your report:n'
for row in bases:
print('Data1 =', row[0],'|','Data2 =', row[1])
message = message + 'Data1 is ' + row[0] + ' and Data2 is ' + row[1] + 'n'

这就是你想做的吗?(如果是,你可以将其标记为答案,如果不是,请告诉我,你需要任何进一步的帮助:(

最新更新