简体   繁体   English

仅在 Python 文件中导入函数

[英]Importing functions only in Python files

I'm a newbie, writing 2 functions in separate files (weather.py, TTS_phrase.py) in the same directory, to then use together:我是新手,在同一目录中的单独文件(weather.py,TTS_phrase.py)中编写 2 个函数,然后一起使用:

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

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

and

def talk(text_to_convert)
  [My code].save(filename)
  print("Done")

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

They both work fine independently.他们都可以独立工作。 When I create a new py file, import both functions ONLY, not the parts after it, it still seems to run the whole py file, not JUST the function.当我创建一个新的 py 文件时,只导入两个函数,而不是它之后的部分,它似乎仍然运行整个 py 文件,而不仅仅是 function。

import weather as w
import TTS_phrase as TTS

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

The indents are correct.缩进是正确的。 It's asking me for inputs and tries to save 2 files when I run this code.当我运行此代码时,它要求我输入并尝试保存 2 个文件。 Am I doing something wrong?难道我做错了什么? I'd really appreciate a steer.我真的很感激一个指导。 Thanks.谢谢。

first you must understand that whenever a file is imported the whole script must run, so you can make a check: and exclude code you dont run on execute like this:首先,您必须了解,每当导入文件时,整个脚本都必须运行,因此您可以进行检查:并排除您在执行时不运行的代码,如下所示:

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

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

and

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM