仅在Python文件中导入函数

仅在Python文件中导入函数,python,function,import,module,Python,Function,Import,Module,我是一个新手,在同一目录下的单独文件(weather.py、TTS_phrase.py)中编写两个函数,然后一起使用: def weather_now(my_town) [My code] return ("Sunny skies") city = input("City Name : ") print(weather_now(city)) 及 他们两人都能独立工作。当我创建一个新的py文件时,只导入两个函数,而不是它后面的部分,它似乎仍然运行

我是一个新手,在同一目录下的单独文件(weather.py、TTS_phrase.py)中编写两个函数,然后一起使用:

def weather_now(my_town)
  [My code]
  return ("Sunny skies")

city = input("City Name : ")
print(weather_now(city))

他们两人都能独立工作。当我创建一个新的py文件时,只导入两个函数,而不是它后面的部分,它似乎仍然运行整个py文件,而不仅仅是函数

import weather as w
import TTS_phrase as TTS

text1 = w.weather_now("London")
TTS.talk(text1)

缩进是正确的。当我运行此代码时,它要求我输入并尝试保存2个文件。我做错什么了吗?我真的很喜欢一头牛。谢谢。

首先,您必须了解,无论何时导入文件,整个脚本都必须运行!因此,您可以进行检查,排除不在其上运行的代码,执行方式如下:

def weather_now(my_town)
  [My code]
  return ("Sunny skies")

if __name__ == "__main__":
    city = input("City Name : ")
    print(weather_now(city))


这不处理导入协议,如OP请求。您确定吗?因为我不这么认为…哦!是的,它似乎导入了整个脚本,因此要求我输入。我想我可以简单地将函数作为脚本的一部分调用,而不调用整个脚本。我添加了“if name”部分,它们都修复了它。对不起,我还没有了解他们,也没有遇到他们。非常感谢。这让我快发疯了(!)
def weather_now(my_town)
  [My code]
  return ("Sunny skies")

if __name__ == "__main__":
    city = input("City Name : ")
    print(weather_now(city))
def talk(text_to_convert)
  [My code].save(filename)
  print("Done")

if __name__ == "__main__":
    t = input("What text would you like to convert to speech?\n")
    talk(t)