我怎么能让一个python文件运行另一个?
例如,我有两个.py文件。我希望运行一个文件,然后让它运行另一个.py文件。
我怎么能让一个python文件运行另一个?
例如,我有两个.py文件。我希望运行一个文件,然后让它运行另一个.py文件。
当前回答
你可以使用这个脚本:
def run(runfile):
with open(runfile,"r") as rnf:
exec(rnf.read())
语法:
run("file.py")
其他回答
有很多方法。我将按照倒偏好的顺序列出它们(即,最好的在前,最差的在后):
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. 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 Spawn a shell process: os.system('python file.py'). Use when desperate.
你可以用下面的代码运行你的.py文件:
import os
os.system('python filename.py')
注意: 将该文件放在与python主文件相同的目录中。
我使用subprocess。调用它就像subprocess一样。Popen
from subprocess import call
call(["python", "your_file.py"])
您可以将其中一个文件视为python模块,并让另一个文件导入它(就像导入标准python模块一样)。后者可以引用导入模块中定义的对象(包括类和函数)。模块还可以运行所需的任何初始化代码。参见http://docs.python.org/tutorial/modules.html
它可以在主脚本中被称为abc.py,如下所示:
#!/usr/bin/python
import abc
Abc.py可能是这样的:
print'abc'