0

I have 2 python scripts. First python script name is "test_1.py" and internally it has main() function, and second script is "test_2.py" and internally it has a method called "sub_main()". Like wise I can have

test_3.py, test_4.py etc

Now in my "test_1.py I am trying to import "test_2.py" dynamically i.e the user will send the file name in command line arguments and I will store it in a variable and using this variable I should be able to import that respective script and call the "sub_main()" in my "main()" method of "test_1.py". Is there a workaround for this?

1
  • 1
    i think it's an x y problem i think the real question is why do you need those dynamic imports ? Commented Aug 11, 2022 at 13:01

2 Answers 2

1

You can use:

import importlib

module_name = input('Enter a module name you want')
dynamically_imported_module = importlib.import_module(module_name)
Sign up to request clarification or add additional context in comments.

Comments

0

You can obtain the name of the module you want to import from the command line arguments, put it into a variable, use that in an f string and exec() that f string:

st = f"import {name_of_module_to_be_imported}"
exec(st)

Whether that is a good idea is, of course, another question. You're opening yourself up to all sorts of security exploits where somebody could inject malicious code into the command-line arguments, which you will then execute.

Comments

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.