call a function in python script then check if condition

假如想象 提交于 2019-12-24 22:06:44

问题


I have this function:

def ContentFunc():
        storage = StringIO()
        c = pycurl.Curl()
        c.setopt(c.URL, url)
        c.setopt(c.WRITEFUNCTION, storage.write)
        c.perform()
        c.close()
        content = storage.getvalue()


while True:
        ContentFunc()
        if "word" in content:
             out = open('/tmp/test', 'a+')

I want to append content from content = storage.getvalue(). But doesn't work.

The ERROR:

NameError: name 'content' is not defined

Can you help me?


回答1:


In your function

def ContentFunc():
    ...
    content = storage.getvalue()

This defines content within the scope of that function. The function then ends, and that name (and the object assigned to it) is discarded. Instead, return from the function:

def ContentFunc():
    ...
    return storage.getvalue()

and assign the name in the calling function:

content = ContentFunc()


来源:https://stackoverflow.com/questions/23833697/call-a-function-in-python-script-then-check-if-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!