简体   繁体   English

如何使用单个 python(.py) 脚本运行多个 python 脚本

[英]How to run multiple python scripts using single python(.py) script

I have written multiple python scripts that are to be run sequentially to achieve a goal.我编写了多个 python 脚本,这些脚本将按顺序运行以实现目标。 ie: IE:

my-directory/ a1.py, xyz.py, abc.py, ...., an.py我的目录/ a1.py, xyz.py, abc.py, ...., an.py

All these scripts are in the same directory and now I want to write a single script that can run all these.py scripts in a sequence.所有这些脚本都在同一个目录中,现在我想编写一个可以按顺序运行所有这些.py 脚本的脚本。 To achieve this goal, I want to write a single python(.py) script but don't know how to write it.为了实现这个目标,我想写一个单独的 python(.py) 脚本,但不知道怎么写。 I have windows10 so the bash script method isn't applicable.我有 windows10,所以 bash 脚本方法不适用。

What's the best possible way to write an efficient migration script in windows?在 windows 中编写高效迁移脚本的最佳方法是什么?

using a master python script is a possibility (and it's cross platform, as opposed to batch or shell).可以使用主 python 脚本(它是跨平台的,而不是批处理或 shell)。 Scan the directory and open each file, execute it.扫描目录并打开每个文件,执行它。

import glob,os
os.chdir(directory)  # locate ourselves in the directory
for script in sorted(glob.glob("*.py")):
    with open(script) as f:
       contents = f.read()
    exec(contents)

(There was a execfile method in python 2 but it's gone, in python 3 we have to read file contents and pass it to exec , which also works in python 2) (在 python 2 中有一个execfile方法,但它不见了,在 python 3 中我们必须读取文件内容并将其传递给exec ,这在 python 2 中也有效)

In that example, order is determined by the script name.在该示例中,顺序由脚本名称确定。 To fix a different order, use an explicit list of python scripts instead:要修复不同的顺序,请改用 python 脚本的显式列表:

for script in ["a.py","z.py"]:

That method doesn't create subprocesses.该方法不会创建子流程。 It just runs the scripts as if they were concatenated together (which can be an issue if some files aren't closed and used by following scripts).它只是运行脚本,就好像它们被串联在一起一样(如果某些文件没有关闭并被后续脚本使用,这可能是一个问题)。 Also, if an exception occurs, it stops the whole list of scripts, which is probably not so bad since it avoids that the following scripts work on bad data.此外,如果发生异常,它会停止整个脚本列表,这可能还不错,因为它避免了以下脚本处理错误数据。

You can name a function for all the script 2 like this:您可以像这样为所有脚本 2 命名 function:

script2.py
def main():
    print('Hello World!')

And import script2 function with this:并使用以下命令导入 script2 function:

script1.py
from script2.py import *
main()

I hope this is helpful (tell me if I didn't answer to your question I'm Italian..)我希望这对您有所帮助(如果我没有回答您的问题,请告诉我我是意大利人……)

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

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