Page 1 of 1

How to exec py-file as a main.py replacement?

Posted: Tue Nov 24, 2020 2:18 pm
by mcc
Hi,

I simply don't know how to create a search string for this possibly super simple question...

I want to create a main.py which consists of several expressions, which directly execute
other *.py files (named in the main.py) in sequence with the same effect, as if their code
would be included in the main.py.
Beside the name of the files themselves there should be a less information about the contents
of those files in the main.py as possible...

Is this even possible and if yes...how?

Cheers!
mcc

Re: How to exec py-file as a main.py replacement?

Posted: Tue Nov 24, 2020 2:32 pm
by Divergentti
Perhaps this thread helps viewtopic.php?t=6179

Re: How to exec py-file as a main.py replacement?

Posted: Tue Nov 24, 2020 10:19 pm
by jimmo
In Python, when you "import foo" it executes the contents of foo.py

If you want to "re-import" it, you can "del" it from sys.modules first.

So if I have foo.py:

Code: Select all

print("hello")
then in main.py I can run

Code: Select all

for i in range(5):
  import foo
  del sys.modules['foo']
to run the contents of foo.py five times. Or if I just wanted to run a few different modules once each, I could just import them one after the other.

Re: How to exec py-file as a main.py replacement?

Posted: Wed Nov 25, 2020 12:51 pm
by stijn
Alternative to the above, less 'magic':

foo.py:

Code: Select all

def Foo():
  print("hello")
main.py:

Code: Select all

import foo
for i in range(5):
  foo.Foo()