4

I have written multiple python scripts that are to be run sequentially to achieve a goal. i.e:

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?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Eisha Tir Raazia
  • 327
  • 3
  • 11
  • 1
    Why not import the other scripts into this script, then just use their methods? – Brenden Price Sep 22 '20 at 19:24
  • 1
    Take look at this [Run multiple python scripts concurrently](https://stackoverflow.com/questions/28549641/run-multiple-python-scripts-concurrently#:~:text=You%20can%20run%20multiple%20instances,then%20run%20your%20client%20code.) – Ajay Verma Sep 22 '20 at 19:25
  • 1
    _multiple python scripts that are to be run sequentially_ Seems like a good use for a batch file. – John Gordon Sep 22 '20 at 19:26
  • 2
    You can use the [subprocess](https://docs.python.org/3/library/subprocess.html) module from the standard library. – darcamo Sep 22 '20 at 19:28

2 Answers2

6

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

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

Matteo Bianchi
  • 434
  • 1
  • 4
  • 19