简体   繁体   English

如何从另一个python文件执行三个.py文件?

[英]How to execute three .py files from another python file?

我需要另一个将执行这3个脚本的python脚本。

You probably want the following : 您可能需要以下内容:

import os

def include(filename):
if os.path.exists(filename): 
    execfile(filename)


include('myfile.py')

But I think it would be better to refactor your code using functions and use import . 但是我认为使用函数和import来重构代码会更好。 There already was similar questio at SO: 目前已是类似questio在SO:

import - will execute code which you import (once) 导入-将执行您导入的代码(一次)

os.system("scriptname.py") 使用os.system( “scriptname.py”)

subprocess

popen POPEN

Put the python code to be called into a namespace/module that is visible to python through sys.path and import the methods/classes in your secondary .py files. 将要调用的python代码放入通过sys.path对python可见的名称空间/模块中,然后将方法/类导入辅助.py文件中。 That way you can directly access the code and execute it the way you require. 这样,您可以直接访问代码并以所需的方式执行代码。

Like other answers already suggest you could execute the code in your secondary files directly but I would personally always prefer to package it up and import it - it's much cleaner and easier to maintain as you can do more selective changes to the code in your secondary files without affecting any part that imports already existing parts of it. 像其他答案一样,您可以直接在辅助文件中执行代码,但是我个人总是愿意打包并导入它-它更清洁,更易于维护,因为您可以对辅助文件中的代码进行更多选择性更改而不会影响导入其现有零件的任何零件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM