-1

For example I have a variable config in config.py. I want to use the variable config in main.py. And the config.py must be pass to main.py through command line. like follows:

python ./main.py ./config.py

I know in lua I can use dofile function. How can I do this in Python

Fixed by Dynamic module import in Python

Community
  • 1
  • 1
Samuel
  • 5,977
  • 14
  • 55
  • 77

2 Answers2

0

disclaimer: i cant comment

can you just import the variable in main.py ?

from .config import config

#do stuff

the only other way i could imagine this would work, if you would pipe the line to the main.py file and parse it by hand or something:

cat config.py | grep 'config = ' | sed -e 's,config = ,,g' | python main.py

thou this will only work if config is only used once in the file and the value it represents is behind the = and you know if it is a string or a int etc.

yamm
  • 1,523
  • 1
  • 15
  • 25
0
# main.py
import sys
import os

if __name__ == "__main__":
    var_name = "config"
    arg = sys.argv[1]
    module_path = os.path.realpath(os.path.dirname(arg))
    if module_path not in sys.path:
        sys.path.insert(0, module_path)

    module_name = os.path.basename(arg).replace(".py", "")
    module = __import__(module_name)
    config_var = getattr(module, var_name)
    # use config_var
pavel_form
  • 1,760
  • 13
  • 14