0

I have a simple game and I want to decide the bots that play it by selecting their files through the command line. Each bot has a take_turn function that returns a digit and that is it.

The command line would be something like:

python game.py ttt_log.txt random_bot.py draw_bot.py

I'm not sure how to import the files and then use their functions. They are currently being read using argv.

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
ri-chard
  • 11
  • 3
  • 3
    See this related: [Dynamic module import in Python](http://stackoverflow.com/questions/301134/dynamic-module-import-in-python). – jedwards Mar 07 '15 at 00:14
  • If you are importing functions from a different python file, you need to `import` it inside `game.py` assuming that is your main file – letsc Mar 07 '15 at 00:15

1 Answers1

2

To dynamically import modules given their file path, Python provides the imp (as in import) module. Please note there are significant changes between Python 2 and 3 (and even recent Py 3 minor versions), so read the doc for more information.

Example usage, you can adapt it to your needs:

import imp
import sys
import os

module_path = sys.argv[1]
module_name = os.path.splitext(module_path)[0]

mymodule = imp.load_source(module_name, module_path)

result = mymodule.take_turn()

print("The result is: {}".format(result))
zopieux
  • 2,854
  • 2
  • 25
  • 32