0

I have a main py script which imports a second py script which is used many times in main.py with a fresh start. Now how can I de import the script and run it again. I want to run the whole script and not some function of the script.

I have tried running it dynamically which now I know doesn't works on scripts and only on proper modules.

#main.py
for i in range(5):
    import second

#second.py
print(....)
2
  • 3
    this is generally a very un-python way of doing things. What exactly are you trying to achieve by structuring your code like this? Why do you want to import it again and again? There is probably a better solution if you can elaborate? Commented Jul 5, 2019 at 21:34
  • 1
    @user3235916 This has its uses.. Generally if you don't own/ don't have access to mutate the module being executed then this is the cheapest way to get runtime re-use. If you do have the ability to update the file, then yes, you should go another way, like nesting the re-usable components in a method. Commented Jul 5, 2019 at 21:40

1 Answer 1

2

you could try using the importlib module:

import importlib
for i in range(5)
    importlib.load_module(second)

or the imp module though this is depreciated and thus not recommended.

import imp
for i in range(5)
    imp.reload(second)
Sign up to request clarification or add additional context in comments.

1 Comment

This API is deprecated. Use importlib.import_module

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.