简体   繁体   中英

Reference for code in given string

I'm running an automated messaging service that sends HTML and plain-text e-mails. The script that I'm using will receive 3 parameters. To, subject and a string that contains 4 different types of data.

The problem is, I can't figure out how to reference these four values seperately. I've done a couple of attempts with sys.argv[3], which should display these given arguments. The question I have is, how do I get Python to recognize these as 4 different values, instead of one string? Because I to reference them in the e-mails I've written, which are written into the code itself.

 #!/usr/bin/env python

list1=[0,1,2,3,4];

import mimetypes, os, smtplib, sys, untangle
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
from email.utils import make_msgid

me = "xx@yy.nl"
you = "yyy@xx.nl"
DESTINATION=sys.argv[1]
SUBJECT=sys.argv[2]
MESSAGE=sys.argv[3]
PASS='yyyxxxyyy'
SRVSMTP='mysmtpsever:587'

msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = me
msg['To'] = you
msg['Date'] = formatdate()
msg['Message-ID'] = make_msgid()

text = """
email with references here
"""
html = """
html email with references here 
"""

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

smtpserver = smtplib.SMTP(SRVSMTP)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(me, PASS)

smtpserver.sendmail(me, you, msg.as_string())
smtpserver.quit()

The string the monitoring system pastes is in BASH. What I had in mind is something the lines of XML's working, like this.

<Root>
<Child1> {HOST.NAME} </Child1>
<Child2> {TRIGGER.NAME} </Child2>
<Child3> {TRIGGER.STATUS} </Child3>
<Child4> {TRIGGER.SEVERITY} </Child4>
</Root>

I feel like I'm thinking into the right direction, but I can't wrap my head around this. Any advice is appreciated.

So since you said you can complete control the third parameter, I would suggest separating the four elements of the parameter with a symbol that will not occur in the elements. Often the semicolon ; is used for that, but you can use any character you want. You would than get these elements with the following python line:

element1, element2, element3, element4 = sys.argv[3].split(';')

If for some reason you want to use xml, you can do that:

import xml.etree.ElementTree as ET
root = ET.fromstring(sys.argv[3])
child1, child2, child3, child4 = (c.text for c in root.children)

You can use this if you cant gurrantee that one character will not be in the text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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