如何让一个 python 文件运行另一个? [英] How can I make one python file run another?

查看:52
本文介绍了如何让一个 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):

  1. 将其视为模块: 导入文件.这很好,因为它安全、快速且可维护.代码被重用,因为它应该完成.大多数 Python 库使用跨越大量文件的多种方法运行.强烈推荐.请注意,如果您的文件名为 file.py,则您的 import 应该在结束.
  2. 臭名昭著(且不安全)的exec 命令:strong> 不安全、笨拙,通常是错误的答案.尽可能避免.
    • execfile('file.py') 在 Python 2 中
    • exec(open('file.py').read()) 在 Python 3 中
  1. 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 called file.py, your import should not include the .py extension at the end.
  2. 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

这篇关于如何让一个 python 文件运行另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆