要在Python中执行另一个Python文件,您可以使用import语句将目标文件导入为模块,然后调用其函数或使用其变量
假设我们有两个Python文件:main.py和other_file.py。
other_file.py内容如下:
def hello():
print("Hello from other_file!")
x = 10
要在main.py中执行other_file.py中的代码,请按照以下步骤操作:
main.py文件。main.py中,导入other_file模块:import other_file
other_file中的函数:other_file.hello()
other_file中的变量:print(other_file.x)
最终的main.py文件应如下所示:
import other_file
other_file.hello()
print(other_file.x)
运行main.py后,您将看到以下输出:
Hello from other_file!
10