2

If I use this code:

parser.add_argument('-d', '--directory', type=str, metavar='', required=True,
                help='Directory that files in question are located.')
parser.add_argument('-f', '--filename', type=str, metavar='', required=False,
                help='filename without .py extension.')

module_path = args.directory
file_name = args.filename
sys.path.append(module_path)

And now I want to print some variable within that file doing something like this:

import file_name
print(file_name.flight_date)

With this I get the error that file_name is not a module. Now if I go in and manually enter the value that file_name has stored then I have no problems. I do not want to manually put this in the script though because the value of file_name will change with different command line arguments.

I want the variable value to be what I am importing and not the variable itself but I do not know how to do that.

Thanks in advance!

chash
  • 3,975
  • 13
  • 29

1 Answers1

3
import importlib

i = importlib.import_module(file_name)

In your case then it'd be print(i.flight_date) after that

GLaw1300
  • 195
  • 9