首页 > 解决方案 > 导入自定义函数时出错

问题描述

当我尝试从文件中导入函数时,它无法识别我之前导入的模块,而直接定义时则没有问题。

该模块作为 sr 导入。我应该导入它的函数体还是有任何其他技巧。

    # doesn't work
    import speech_recognition as sr
    r = sr.Recognizer()

    from Chatfunctions import Listner



    Listner()
    ---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-720eb32cc560> in <module>()
      7 
      8 
----> 9 Listner()
     10 

/Users/michalczapski/Bots/BI Bot/Chatfunctions.py in Listner()
     12     print("Botty: ",message)
     13     return None
---> 14 
     15 def Listner():
     16     with sr.Microphone() as source:

NameError: name 'sr' is not defined


    # works
    import speech_recognition as sr
    r = sr.Recognizer()


    def Listner():
        with sr.Microphone() as source:
            print("...")
            audio=r.listen(source)

          try:
            print("You: "+r.recognize_google(audio));
            return r.recognize_google(audio)
          except:
            pass;
    Listner()

标签: pythonimport

解决方案


导入函数中用到的所有模块都需要导入到定义函数的文件中


推荐阅读