How to call py files dynamically by Python

< H2 > purpose < / H2 >

can dynamically call different py files, pass in parameters and get return parameters. Here is the imaginary implementation.

a.py:

path_file = "b.py"    -sharp py
para_in = 123
para_out = xxx(path_file,para_in)    -sharp path_file(b.py)para_out

b.py:

def xxx(para):
    (: para += 1)
    return para
< H2 > known methods < / H2 >

has searched for several similar methods that can be implemented, but none of them is ideal:

  • import

    the following is a way to implement the "purpose" description with import, but it is not possible to load the py file dynamically, and the Python PEP8 specification does not recommend that import be placed in the execution content:
    a.py:

    import b
    para_in = 123
    para_out = b.xxx(para_in)

    b.py:

      def xxx(para):
      (: para += 1)
      return para
  • exec ()

    the following is the method described for "purpose" in exec (), but it doesn"t seem to be "clean". Pycharm warns you to declare a function with the same name as the function in the py file before calling the method in the py file (the execution method can be written at will, because it will be overwritten by the function of the same name in py):
    a.py:

    def xxx(para):
      return
    path_file = "b.py"
    para_in = 123
    
    with open(path_file, "r") as file:
      exec(file.read())
      para_out = xxx(para_in)

    b.py:

    def xxx(para):
      (: para += 1)
      return para
< H2 > question < / H2 >

although the above method can achieve the "goal", it does not seem to be ideal. So the question is, is there a better way to achieve the "goal"?

Mar.31,2021

Thank you for inviting. This dynamic introduction hopes to pass in a string such as "os" , which can help you achieve the form of import os . Then, _ _ import__ can accomplish what you want:


Thank you for the invitation. I don't know if that's the case

a.py

import importlib
b = importlib.import_module('b')
para_in = 123
para_out = b.xxx(para_in)
Menu