lambda函数不打印值而是打印对象值

时间:2017-01-27 20:51:31

标签: python python-3.x lambda output

我有一个脚本,通过电子邮件将链接发送给我。

问题是链接不包括在内,而是我得到:

<function <lambda> at 0x7f75b5fb4a60>

我的脚本如下:

from bs4 import BeautifulSoup
import re
import requests

ex_webdev_js_by_city = [
'http://boston.website.org/search/web',
]

ex_web_j_keywords = [['one'],['coool', 'person']]
ex_web_j_keywords = sum(ex_web_j_keywords, [])

ex_js = []

for webdev_j_for_a_city in ex_webdev_js_by_city:
    webdev_j = requests.get(webdev_j_for_a_city)
    soup = BeautifulSoup(webdev_j.text, "lxml")
    for j_keyword in ex_web_j_keywords:
        for a in soup.find_all('a', class_="result-title hdrlnk", text=re.compile(j_keyword,re.IGNORECASE)):
            #print(a.get('href'))
            ex_js.append(a.get('href'))

if ex_js:
   #email them to myself!
   import smtplib, socket
   TO = 'myemail@gmail.com'

   try:
       server = smtplib.SMTP('smtp.gmail.com', 587)
       server.starttls()
       TEXT = lambda: print(('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js))
       #Gmail Sign In
       gmail_sender = 'myemail'
       gmail_passwd = 'mypass'
       server.login(gmail_sender, gmail_passwd)
       msg = str(TEXT)
       server.sendmail(gmail_sender, gmail_sender, msg)
       print('Sent you some links!')
       server.quit()
   except socket.error as e:
       print ('error sending mail, error was {}'.format(e))

错误发生在这一行(我相信):

lambda: print(('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js))

它似乎打印出电子邮件中的object details给我,而不是value

因此,我在这里可能做错了什么?

2 个答案:

答案 0 :(得分:4)

我不知道你为什么要使用printlambda。如果您只是写道:

msg = ('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js)

并删除:

msg = str(TEXT)
它应该可以工作。

因此try块应为:

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
msg = ('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js)
#Gmail Sign In
gmail_sender = 'myemail'
gmail_passwd = 'mypass'
server.login(gmail_sender, gmail_passwd)
# msg = str(TEXT) !!commented out!! (only to make it explicit)
server.sendmail(gmail_sender, gmail_sender, msg)
print('Sent you some links!')
server.quit()

但我认为你并不真正理解lambdaprint应该做什么。 print使用将数据写入标准输出通道,但是您想将其写入电子邮件,因此您无需在本地打印,您需要以某种方式存储您的消息内存中的

最后lambda:...用于创建匿名函数,如果你不提供任何参数,它的用法通常是推迟执行(例如实现懒惰)。但实际上你需要消息,所以再次不需要使用这个构造。

答案 1 :(得分:1)

当你说

TEXT = lambda: print(('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js))

哟只是简单地创建lambda函数,它还没有被执行。要执行,您需要通过调用TEXT()

来专门调用它

为了解决您的问题更改

TEXT = lambda: ('Latest js from site:\n\n{}'*len(ex_js)).format(*ex_js)

msg = str(TEXT())