0

I have a list of .py file that I need to run sequentially. I usually do it manually, one by one.

Anyway I'd like to have a .py file by which I run these .py automatically.

In R I usually use the command source:

Source (file1, file2 etc)

Is there a way to do anything similar in python? By the way, I use IDLE, so I'd like to have a solution using this program.

Thank you in advance

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52
piravi
  • 109
  • 1
  • 6
  • You could try `import file1, file2`. That will import all the modules, which means running them. However, they won't be the `__main__` module. So anything inside a `if __name__ == '__main__'` block won't be run. Each file will also run in its own namespace. I suspect `Source` runs all those files in the same namespace. – Dunes Oct 05 '20 at 11:49
  • IDLE should not be relevant, anymore than any other IDE. Your code is executed by python, not the IDE feeding your code. – Terry Jan Reedy Oct 05 '20 at 15:09

2 Answers2

0
execfile(filename) 

is probably what you want to use

for instance if you have a list of files to run e.g.

files_to_run = ["path_to/File1", "path_to/File2", "path_to/File3", "path_to/File4"]

for file in files_to_run:
    execfile(file)
0

simple import technically executes the file.

In python, it is common practice to use to define all the required functions int he module and function calls are defined inside if __name__ == "__main__": [means the code inside the if will execute only if the script called directly not when imported]

so that the same module can used as executable and also imported in another file.

Technically, if you did not use if __name__ == "__main__": in your files, simply import itself will execute them.