如何让一个 python 文件运行另一个?
问题描述:
如何让一个 python 文件运行另一个?
How can I make one python file to run another?
例如我有两个 .py 文件.我希望运行一个文件,然后让它运行另一个 .py 文件.
For example I have two .py files. I want one file to be run, and then have it run the other .py file.
答
方法不止几种.我将按照倒置偏好的顺序列出它们(即,最好的在前,最差的在后):
There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):
-
将其视为模块:
导入文件
.这很好,因为它安全、快速且可维护.代码被重用,因为它应该完成.大多数 Python 库使用跨越大量文件的多种方法运行.强烈推荐.请注意,如果您的文件名为file.py
,则您的import
应该不在结束. - 臭名昭著(且不安全)的exec 命令:strong> 不安全、笨拙,通常是错误的答案.尽可能避免.
-
execfile('file.py')
在 Python 2 中 -
exec(open('file.py').read())
在 Python 3 中
-
-
Treat it like a module:
import file
. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is calledfile.py
, yourimport
should not include the.py
extension at the end. -
The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.
-
execfile('file.py')
in Python 2 -
exec(open('file.py').read())
in Python 3
-