要在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
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:python怎么执行python文件