0

I would like to know if it is possible to select python scripts and have them run one after the other. So the first python script runs and gives me the desired result, after this I want another script to run. Example:

Imagine we have 3 scripts: code1.py, code2.py and code3.py. Now I would like to create something that would allow me to run first code1.py, then after that is done run code2.py and finally code3.py.

Is this possible?

P.S- Apologies for not displaying an attempt, I don't have sufficient coding knowledge to be able to do an attempt.

DPM
  • 845
  • 7
  • 33

2 Answers2

2

It sounds like using functions from another file is what you're after

from code1 import do_first_thing
from code2 import do_second_thing
from code3 import do_third_thing

def main():
  do_first_thing()
  do_second_thing()
  do_third_thing()
Ted Brownlow
  • 1,103
  • 9
  • 15
1

IF your scripts are not functions, you can just import them one after an other (if they are in the same folder). Like that they will run on after an other

import code1
import code2
import code3
# And so on...
Manu N.
  • 26
  • 1
  • What if they are in different folders? Does writing the path work? – DPM Jan 16 '21 at 19:55
  • 1
    @DPM By default you can't. but there is an answer [here](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder) – Manu N. Jan 16 '21 at 20:17
  • Note that if you import two or more times the same module (e.g. `code1`) in the same process, then python will not execute that script multiple times, as it was already imported. This is done by python for obvious reasons and to avoid infinitely looping on import cycles. (To OP: this is one of the reasons why you may want to structure your code in functions and classes, and not only in scripts) – Matteo T. Jan 16 '21 at 22:54
  • 1
    Technically you can still reload an import with: `import importlib` and then `importlib.reload(code1)`. You can also put it in a loop if you want – Manu N. Jan 16 '21 at 23:37