Script Python sin importar biblioteca de Knime

Hola que tal apenas estoy adentrandome en el mundo de Knime y estoy intentando enviar un correo por medio de un script de python. La entrada es un archivo de excel y quiero mandar ese archivo por correo pero no lo he logrado porque me pide que importe la librería de Knime y agregué un output pero no entiendo como hacer eso sin tener que estar importando la librería y no sé si haya un operador para hacer eso, espero me puedan ayudar.
image

1 Like

@MartelKhan Bienvenido al foro KNIME. Puedes enviar correos electrónicos a través de los nodos knime.

Sobre python podrías empezar leyendo la guía oficial y usar la integración de Python incluida como inicio.

https://docs.knime.com/latest/python_installation_guide/#_introduction

La traducción se ha realizado utilizando DeepL DeepL Translate: The world's most accurate translator


Welcome to the KNIME forum. You can actually send emails thru knime nodes.

About python you could start by reading the official guide and use the bundled Python integration as a start.

https://docs.knime.com/latest/python_installation_guide/#_introduction

Translation has been done using DeepL DeepL Translate: The world's most accurate translator

4 Likes

Hola @mlauber71 gracias por la respuesta, lo que estoy intentando hacer es mandar un excel ya con formato usando xlswriter por eso necesito el python para poder enviarlo, el código está funcionando ya lo probé en un editor pero acá me pide una tabla de salida y es lo que no sé hacer. Dejo el código # Librerias

import pandas as pd
import numpy as np
import os
import zipfile
import smtplib
import win32com.client as win32
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from datetime import datetime
from xlsxwriter.utility import xl_range,xl_rowcol_to_cell
from pathlib import Path
import time
from pywintypes import com_error
import re
import sys
win32c = win32.constants
from dateutil.tz import tzutc, tzlocal

Escribimos Excel

def rm_main(data):

writer=pd.ExcelWriter('Archivo.xlsx',engine='xlsxwriter', datetime_format='dd/mm/yyyy hh:mm:ss')

data.to_excel(writer,'Archivo',startrow=1,startcol=0, index = False)


workbook = writer.book

Encabezado = workbook.add_format({'bold': True,'font_color': 'white','fg_color': '#002060','border': 1})
Dinero = workbook.add_format({'num_format': '_-$* #,##0.00_-;-$* #,##0.00_-;_-$* "-"??_-;_-@_-'})
Cantidad = workbook.add_format({'num_format': '_-$* #,##0.00_-;-$* #,##0.00_-;_-$* "-"??_-;_-@_-'})
FechaCorta = workbook.add_format({'num_format': 'dd/mm/yyyy'})
Numero = workbook.add_format({'num_format': '0'})


worksheet = writer.sheets['Archivo']

writer.save()


path = "Archivo.xlsx"



z = zipfile.ZipFile('Archivo.zip', 'w')

z.write(path)                   # has to exist

z.close()



path2 = "Archivo.zip"


fromaddr = "servicios@linqsy.site"
toaddr = ["mreyes@linq.mx"]


msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] =  ", ".join(toaddr)
msg['Subject'] = "ArchivoExcel"
 

body ="Este es un correo automatizado, favor de no responder al destinatario, para cualquier duda escribir a mreyes@linq.com.mx"

part = MIMEBase('application', "octet-stream")
part.set_payload(open(path2, "rb").read())
encoders.encode_base64(part)

part.add_header('Content-Disposition', 'attachment; filename="Archivo.zip"')

msg.attach(part)
msg.attach(MIMEText(body, 'html'))
 
server = smtplib.SMTP('mail.linqsy.site', 587)
server.starttls()
server.login(fromaddr,"password")
text = msg

server.sendmail(fromaddr, toaddr, msg.as_string())
server.quit()
return 0

Hola @MartelKhan

Creo que lo que te está ocurriendo es un tema de la pre-configuración del nodo. Como ves el nodo tiene predefinido un puerto de salida, por lo que tienes 2 opciones:

  1. Remover el puerto de salida1 ‘output_table_1’, en los tres puntitos o ellipsis
    image

  2. Darle una salida enviando un pd.DataFrame al puerto, puede ser cualquier cosa: una variable un mensaje; pero eso sí, en formato pandas.

salu2

2 Likes

@MartelKhan maybe you take a look at this example. Doing the formats in Python with the new bundled Python integration 4.7 and then saving the Excel file and sending that via mail thru KNIME.


@MartelKhan tal vez usted echa un vistazo a este ejemplo. Hacer los formatos en Python con la nueva integración de Python 4.7 y luego guardar el archivo de Excel y enviar por correo a través de KNIME

2 Likes

Hola, perdón ya no había respondido a sus comentarios @gonhaddock hice lo que me comentaste pero no he podido encontrar la solución, al quitarle el puerto de salida no me marca error pero no hace algo, no escribe el excel y no envía correo, entonces no sé si este funcionando, hice esto para ver si me tomaba los datos de entrada(Excel)

image
así corre, pero como comentaba no hace algo o no sé si lo hace y si le agrego el puerto de salida me marca esto


No sé si así lo estoy haciendo bien, espero sus comentarios y gracias por la ayuda.

Hola MartelKhan,

me parecen que son dos cosas:

Primero, en lo que vemos en tu script, el método rm_main es definido, pero no ejecutado. Hazlo con rm_main(input_table) despues de la definición del método. Si este no es el problema, porfa, envía el código.

Segundo, tu último screenshot no muestra el contenido de tu nodo Python Script, porqué lo enviaste? Tu nodo ya no tiene el output port.

Muchos saludos
Steffen

2 Likes

Hola @steffen_KNIME, es que en el primer código no lo tiene pero en el segundo si agrego el puerto de salida pero me marca el error de la imagen. solo tengo como input datos de un excel
image
Y este es el código Python:

Librerias

import pandas as pd
import numpy as np
import os
import zipfile
import smtplib
import win32com.client as win32
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from datetime import datetime
from xlsxwriter.utility import xl_range,xl_rowcol_to_cell
from pathlib import Path
import time
from pywintypes import com_error
import re
import sys
win32c = win32.constants
from dateutil.tz import tzutc, tzlocal
import knime.scripting.io as knio

Escribimos Excel

input_table = knio.input_tables[0].to_pandas()
knio.output_tables[0] = knio.input_tables[0]

def rm_main(input_table):

writer=pd.ExcelWriter('Archivo.xlsx',engine='xlsxwriter', datetime_format='dd/mm/yyyy hh:mm:ss')

output_table = writer

input_table.to_excel(writer,'Archivo',startrow=1,startcol=0, index = False)
#writer = pd.DataFrame(input_table_1.copy())

workbook = writer.book

Encabezado = workbook.add_format({'bold': True,'font_color': 'white','fg_color': '#002060','border': 1})
Dinero = workbook.add_format({'num_format': '_-$* #,##0.00_-;-$* #,##0.00_-;_-$* "-"??_-;_-@_-'})
Cantidad = workbook.add_format({'num_format': '_-$* #,##0.00_-;-$* #,##0.00_-;_-$* "-"??_-;_-@_-'})
FechaCorta = workbook.add_format({'num_format': 'dd/mm/yyyy'})
Numero = workbook.add_format({'num_format': '0'})

#output_table = input_table
worksheet = writer.sheets['Archivo']

writer.save()


path = "Archivo.xlsx"



z = zipfile.ZipFile('Archivo.zip', 'w')

z.write(path)                   # has to exist

z.close()



path2 = "Archivo.zip"


fromaddr = "servicios@linqsy.site"
toaddr = ["mreyes@linq.mx"]


msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] =  ", ".join(toaddr)
msg['Subject'] = "Archivo Excel"
 


body ="Este es un correo automatizado, favor de no responder al destinatario, para cualquier duda escribir a mreyes@linq.com.mx"

part = MIMEBase('application', "octet-stream")
part.set_payload(open(path2, "rb").read())
encoders.encode_base64(part)

part.add_header('Content-Disposition', 'attachment; filename="Archivo.zip"')

msg.attach(part)
msg.attach(MIMEText(body, 'html'))
 
server = smtplib.SMTP('mail.linqsy.site', 587)
server.starttls()
server.login(fromaddr,"password")
text = msg

server.sendmail(fromaddr, toaddr, msg.as_string())
server.quit()
#knio.output_tables[0] = pd.DataFrame(knio.input_tables[0])
return 0

#output_table = input_table.copy()
#knio.output_tables[0] = knio.input_tables[0]

El código (sin inputs u outputs) corre sin problemas en otro programa y me llega el archivo por correo con el formato deseado pero aquí no entiendo muy bien como hacerle.

Saludos y gracias por la ayuda.

@MartelKhan what is the error message? What part does not work

Then I would suggest you read about the input and output ports and data and see what you really need and remove the rest.

@MartelKhan ¿Cuál es el mensaje de error? Que parte no funciona

Entonces te sugeriría que leyeras sobre los puertos de entrada y salida y datos y veas lo que realmente necesitas y elimines el resto.

https://docs.knime.com/latest/python_installation_guide/index.html#use-nodes

What is this supposed to do?
¿Para qué sirve esto?

This syntax also look wrong with one ’ too much.
Esta sintaxis también se ve mal con un ’ de más.

———

Then you could open the Python script and execute it by code blocks and see where there might be a problem.

Entonces podrías abrir el script Python y ejecutarlo por bloques de código y ver dónde puede haber un problema.

1 Like

Gracias mlauber71,

MartelKhan, si el problema persiste después de probar los sugestiones de mlauber71, porfa, envia un workflow ejemplo y también envia el códiga formateado. No se pueden leer lo que enviaste. Hay funciones de

preformatted text

aquí.

Steffen

1 Like

Hola @mlauber71 ya quité el return 0 que en realidad no es necesario y la parte de
filename=“Archivo.zip”') está bien porque en realidad el código es así: ‘attachment; filename=“Archivo.zip”’, ya no me manda error pero lo que quiero es que se envíe un archivo a mi correo con los ajustes del xlswriter directamente de python, se corre el workflow pero no me da algún resultado.

Dejo la liga: Conecta_PythonExcel – KNIME Community Hub

1 Like

@MartelKhan my suggestions still stands: separate the creation of the Excel file from the sending of the mail.

Then: your example does not contain any data so it is not possible to test it which also would be complicated since all the settings of the mail server would be specific and maybe not work on any other machine.

If you absolutely must use Python I think the next step would be to check all the “Archive.zip” paths which might not work by themselves and might need to be absolute paths (which you could also create).

Does this work outside KNIME? In JUPYTER notebooks?


@MartelKhan mi sugerencia sigue en pie: separa la creación del fichero Excel del envío del correo.

Luego: tu ejemplo no contiene ningún dato por lo que no es posible probarlo lo que además sería complicado ya que todas las configuraciones del servidor de correo serían específicas y quizás no funcionen en cualquier otra máquina.

Si es absolutamente necesario usar Python creo que el siguiente paso sería comprobar todas las rutas “Archive.zip” que podrían no funcionar por sí mismas y necesitar ser rutas absolutas (que también podrías crear).

¿Funciona esto fuera de KNIME? ¿En cuadernos JUPYTER?

Traducción realizada con la versión gratuita del traductor DeepL Translate: The world's most accurate translator


1 Like

Hola MartelKhan,

he visto tu workflow. Como dicho en mi post antes, hay que executar la función:

#import ...
input_table = knio.input_tables[0].to_pandas()

def rm_main(input_table):
    writer=...
    ...


rm_main(input_table) # <-- tienes que executar

Tambíen podrias escribirlo sin el método.

Steffen

3 Likes

Hola @steffen_KNIME, efectivamente era lo que tenía que hacer, muchas gracias por la ayuda a todos.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.