PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 14, 2022

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

 April 14, 2022     migration, python, sequential, windows     No comments   

Issue

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?


Solution

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.



Answered By - Jean-François Fabre
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing