Constantine
Constantine

Reputation: 2032

Python import from command line

My goal is to provide user with ability to dynamicaly choose some strategy, that he can provide as python file in command line. (Ex: myApp -s /some_path/SomeStrategy.py) strategy with proper interface and all other OOP stuff.

So, is there any ability to implement this?

Upvotes: 2

Views: 1084

Answers (2)

Januka samaranyake
Januka samaranyake

Reputation: 2597

Import a module. The name argument specifies what module to import in absolute or relative terms

(e.g. either pkg.mod or ..mod).

If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name

(e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).

importlib.import_module('os.path')

Upvotes: 1

Right leg
Right leg

Reputation: 16710

Say in all your code you interact with a Strategy class, but you never implement it. I think a load method as following should do the trick:

def load(class) :
    global Strategy
    Strategy = class

This way, you just make the variable Strategy point to another class, so in all the code, Strategy refers to the class that the user loaded.

Of course a better way to do this would to have a Application class, with a strategyClass attribute, but the same idea applies.

If you want to load it from the command file, it becomes a little more tricky, but from Python's point of view, the idea stays the same.

Upvotes: 1

Related Questions