简体   繁体   中英

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. ie:

my-directory/ 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. To achieve this goal, I want to write a single python(.py) script but don't know how to write it. I have windows10 so the bash script method isn't applicable.

What's the best possible way to write an efficient migration script in windows?

using a master python script is a possibility (and it's cross platform, as opposed to batch or 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)

In that example, order is determined by the script name. To fix a different order, use an explicit list of python scripts instead:

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:

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

And import script2 function with this:

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..)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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