Python 变量数据类型错误?
我有一个类,用于从Git提交中获取用户名和他的电子邮件:Python 变量数据类型错误?,python,python-2.7,variables,office365,smp,Python,Python 2.7,Variables,Office365,Smp,我有一个类,用于从Git提交中获取用户名和他的电子邮件: class BitbucketData(object): def get_user_name(self): proc = subprocess.Popen("git --no-pager show -s --format='%an'", stdout=subprocess.PIPE) committer_name = proc.stdout.read() if committe
class BitbucketData(object):
def get_user_name(self):
proc = subprocess.Popen("git --no-pager show -s --format='%an'", stdout=subprocess.PIPE)
committer_name = proc.stdout.read()
if committer_name:
return committer_name
def get_user_email(self):
proc = subprocess.Popen("git --no-pager show -s --format='%aE'", stdout=subprocess.PIPE)
committer_email = proc.stdout.read()
if committer_email:
return committer_email
然后,它用于向用户发送通知(底部是工作版本-无变量-所有发送方
和接收方
数据集,不在变量中-他们在此处注释):
使用变量时,代码如下所示:
class Services(object):
def sendmail(self, event):
repo = BitbucketData()
to_address = repo.get_user_email()
#to_address = 'user@domain.com'
to_name = repo.get_user_name()
#to_name = 'Test user'
from_address = 'user@domain.com'
subject = 'Bamboo build and deploy ready'
sender = 'Bamboo agent <user@domain.com>'
text_subtype = 'plain'
message = """
Hello, {}.
Your build ready.
Link to scenario: URL
Link to build and deploy results: {})
""".format(to_name, os.environ['bamboo_resultsUrl'])
msg = MIMEText(message, text_subtype)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = to_name
smtpconnect = smtplib.SMTP('outlook.office365.com', 587)
smtpconnect.set_debuglevel(1)
smtpconnect.starttls()
smtpconnect.login('user@domain.com', 'password')
smtpconnect.sendmail(from_address, to_address, msg.as_string())
smtpconnect.quit()
print('Mail sent')
print(repo.get_user_email())
给我:
看起来您正在从git命令接收以下输出-
"'user@domain.com'\n"
您直接将此消息传递给smtpconnect,这是导致问题的原因,因为这不是有效的电子邮件地址。您可能需要从中获取实际字符串。获得它的一种方法是使用函数。范例-
>>> import ast
>>> e = ast.literal_eval("'user@domain.com'\n")
>>> print(e)
user@domain.com
从get\u user\u email()
函数返回电子邮件时,需要执行此操作。很可能committer\u name
也存在此问题,因此您可能也希望这样做
来自
ast.literal\u eval()的文档-
ast.literal\u eval(节点或字符串)
安全地计算表达式节点或包含Python文本或容器显示的Unicode或Latin-1编码字符串。提供的字符串或节点只能由以下Python文本结构组成:字符串、数字、元组、列表、dicts、boolean和None
你能打印并更新问题中的print(repr(repo.get\u user\u email())
吗?你注意到“'user@domain.com错误代码中的“\n”
是双包装字符串吗?该值实际上包含引号和换行符,因此可能不是有效地址(除非错误代码添加了额外字符)。@SuperBiasedMan是的,我看到了-但无法从“”出现的位置理解:-|@AnandSKumar谢谢,问题已更新。是的-又出现了”
。当您将换行符作为参数传递时,是否尝试过删除引号并剥离换行符?像这样theEmail.replace(“,”).strip()
,你可以看看它是否有效。它不会解决问题的根源,但会让你知道这是否是真正的问题。谢谢,这是有效的。但是-可以用re.sub来完成吗?我现在正在玩它。我想可以,但我不是正则表达式方面的专家:)。我猜这将是一个复杂的规则r表达式。
def sendmail(self, event):
repo = BitbucketData()
print(repr(repo.get_user_email()))
...
...
Creating new AutoEnv config
"'user@domain.com'\n"
send: 'ehlo pc-user.kyiv.domain.net\r\n'
...
"'user@domain.com'\n"
>>> import ast
>>> e = ast.literal_eval("'user@domain.com'\n")
>>> print(e)
user@domain.com