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

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
mcc
Posts: 14
Joined: Fri Oct 30, 2020 4:41 am

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

Post by mcc » Tue Nov 24, 2020 2:18 pm

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

Divergentti
Posts: 67
Joined: Fri Sep 04, 2020 9:27 am
Location: Hanko, Finland
Contact:

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

Post by Divergentti » Tue Nov 24, 2020 2:32 pm

Perhaps this thread helps viewtopic.php?t=6179

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

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

Post by jimmo » Tue Nov 24, 2020 10:19 pm

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.

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

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

Post by stijn » Wed Nov 25, 2020 12:51 pm

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

Post Reply