ri-chard
ri-chard

Reputation: 11

Importing a file given in the command line

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.

Upvotes: 0

Views: 45

Answers (1)

zopieux
zopieux

Reputation: 2901

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))

Upvotes: 2

Related Questions