我怎么能让一个python文件运行另一个?
例如,我有两个.py文件。我希望运行一个文件,然后让它运行另一个.py文件。
我怎么能让一个python文件运行另一个?
例如,我有两个.py文件。我希望运行一个文件,然后让它运行另一个.py文件。
当前回答
from subprocess import Popen
Popen('python filename.py')
或how-can-i-make-one-python-file-run-another-file
其他回答
有很多方法。我将按照倒偏好的顺序列出它们(即,最好的在前,最差的在后):
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.
我使用subprocess。调用它就像subprocess一样。Popen
from subprocess import call
call(["python", "your_file.py"])
让一个python文件运行另一个,使用python 2.7.3和Ubuntu 12.10:
把它放在main.py中: #!/usr/bin/python 进口yoursubfile 把这个放到你的subfile.py中 #!/usr/bin/python 打印(“hello”) 运行该程序: python main.py 它打印: 你好
因此main.py运行你的subfile.py
有8种方法来回答这个问题,一个更规范的答案是:如何导入其他Python文件?
from subprocess import Popen
Popen('python filename.py')
或how-can-i-make-one-python-file-run-another-file
你可以用下面的代码运行你的.py文件:
import os
os.system('python filename.py')
注意: 将该文件放在与python主文件相同的目录中。