可以使用 Python 的内置函数 'execfile()' 或者 'exec()' 来执行另一个 Python 文件。

使用 'execfile()' 函数:

execfile('other_file.py')

使用 'exec()' 函数:

with open('other_file.py', 'r') as f:
    code = f.read()
    exec(code)

其中,'exec()' 函数需要先将文件内容读取出来,然后执行。而 'execfile()' 函数直接执行文件内容。

Python 代码中执行另一个 Python 文件的两种方法

原文地址: https://www.cveoy.top/t/topic/oeR1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录