Python: Dynamically Load Module and Call Functions

28 Mar

I was looking through the videos for PyCon 2013 and there was a talk on Dynamic Code Patterns that caught my attention – because I don’t know what they are. I love the idea of loading plugins but have no idea how to write code that would allow for it. So, without watching the video yet, I took a shot at trying to write some code.

I started at David Janes’ Code Weblog to learn how to dynamically load code. I took his function for my code.

Then I wrote a simple python script with two functions and dropped it in a folder:

def hello(x): print “Hello, ” +x
def add(x): d=x.split(“,”) print int(d[0])+int(d[1])

My first attemt at loading a module and calling the function looked like this:

for (path, dirs, files) in os.walk(‘C:\\Documents and Settings\\user\\Desktop\\test’):
i=0
while(i<len(files)):

#print files[i]
a=load_module(‘C:\\Documents and Settings\\user\\Desktop\\test\\’+str(files[i]))
i+=1
a.hello(“Paul”)
print dir(a)

I load the one file in the folder to variable a. This code is awful. For starters, it grabs all the files – even non .py files – and if there are non .py files it will crash. There will be a .pyc after it executes succesfully once – 2nd attempt will fail. It also counts all the files so the loop will be off (out of index range error). Lastly, I hard coded the function and parameters.

My last attempt was a program that prints out the functions in a module and lets you pick one. It then asks for parameters and then executes the function. It uses getattr() to allow the passing of the function name and method from strings.

for (path, dirs, files) in os.walk(‘C:\\Documents and Settings\\user\\Desktop\\test’):
i=0
while(i<len(files)):

#print files[i]
a=load_module(‘C:\\Documents and Settings\\user\\Desktop\\test\\’+str(files[i]))
i+=1

z=dir(a)
i=0
while(i<len(z)):
if z[i][0]==”_”:
i+=1
else:
print z[i]+”\n”
i+=1

var = raw_input(“Choose a Function: “)
name=raw_input(“parameters: “)
getattr(a,str(var))(str(name))

Here is the full code to my simple attempt to dynamically load a module (plugin) and have it exposed automatically to the user.

import md5
import os.path
import imp
import traceback
import sys

try:
os.remove(‘C:\\Documents and Settings\\user\\Desktop\\test\\extone.pyc’)
except:
pass

def load_module(code_path):
try:
try:
code_dir = os.path.dirname(code_path)
code_file = os.path.basename(code_path)

fin = open(code_path, ‘rb’)

return imp.load_source(md5.new(code_path).hexdigest(), code_path, fin)
finally:
try: fin.close()
except: pass
except ImportError, x:
traceback.print_exc(file = sys.stderr)
raise
except:
traceback.print_exc(file = sys.stderr)
raise

for (path, dirs, files) in os.walk(‘C:\\Documents and Settings\\user\\Desktop\\test’):
i=0
while(i<len(files)):

#print files[i]
a=load_module(‘C:\\Documents and Settings\\user\\Desktop\\test\\’+str(files[i]))
i+=1

z=dir(a)
i=0
while(i<len(z)):
if z[i][0]==”_”:
i+=1
else:
print z[i]+”\n”
i+=1

var = raw_input(“Choose a Function: “)
name=raw_input(“parameters: “)
getattr(a,str(var))(str(name))

 

 

Advertisements

One Response to “Python: Dynamically Load Module and Call Functions”

  1. SutoCom March 29, 2013 at 1:46 am #

    Reblogged this on Sutoprise Avenue, A SutoCom Source.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: