使用asyncio存储属性值

时间:2018-09-24 11:02:22

标签: python python-asyncio

我正在尝试以下代码:

    import asyncio
    import smmrpy

    s = smmrpy.SMMRPY("286C6866B9")
    URL = 'https://stackoverflow.blog/2018/09/13/ibm-and-stack-overflow-partner-to-support-ai-developers/'

    async def main():
        article = await s.get_smmry(URL)

        print(article.content)
        print(article.keywords)

    if __name__ == "__main__":
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())

其中总结了使用SMMRY(https://smmry.com/)和asyncio(提供100个请求的API密钥)的网站。 smmrpy模块创建一个“文章”对象,尽管它可以打印属性,但我无法像通常那样将它们存储在变量/列表中,例如:

    import asyncio
    import smmrpy

    s = smmrpy.SMMRPY("286C6866B9")
    URL = 'https://stackoverflow.blog/2018/09/13/ibm-and-stack-overflow-partner-to-support-ai-developers/'

    async def main():
        article = await s.get_smmry(URL)

        print(article.content)
        print(article.keywords)
        # option 1:
        # content = article.content
        # option 2:
        # return article
        # content = getattr(article, 'content')     

    if __name__ == "__main__":
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())

我想做的是将属性值存储在变量中以进一步导出。关于我在做什么错的任何想法吗?

1 个答案:

答案 0 :(得分:1)

发现问题,问题在于变量作用域。函数内部的变量是局部变量,不能在函数内部定义全局调用。此块可解决问题并打印两次,而不会出现错误:

import asyncio
import smmrpy

s = smmrpy.SMMRPY("286C6866B9")
URL = 'https://stackoverflow.blog/2018/09/13/ibm-and-stack-overflow-partner-to-support-ai-developers/'

async def main():
    article = await s.get_smmry(URL)
    global contents
    contents = article.content  
    print(contents) 
    print(article.keywords)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

print(contents)