-1

I imported a module as below:

filename = "email"
mymodule = __import__('actions.'+filename)

the problem I have with this is, that the file is immediatly executing, and I would much rather execute a specific function from the file (that way I can send variables through it).

I am basically working with plugins, so it works.

Edit: for the time being, I am not concerned with whether or not the script executes when I add the line below:

mymodule = __import__('actions.'+filename)

but what I would like to work is when I add the line below, I would like the function to execute. But instead I get an error that the module dosn't have that function even though it exisits in the script.

mymodule.dosomething(n)

Edit: I personally don't think that the function has anything to do with it but here is one python files that I am trying to open.

import webbrowser
def OpenEmail():
    handle = webbrowser.get()
    handle.open('http://gmail.google.com')
OpenEmail()
print "Your email has been opened"
bs7280
  • 1,074
  • 3
  • 18
  • 32
  • 1
    Please add some more code relevant to the function that doesn't work. – phant0m Aug 05 '12 at 07:56
  • I personally dont think the function has anything to do with it. I have tried it with many different functions and it did not work. Here is the error---- AttributeError: 'module' object has no attribute 'OpenEmail' – bs7280 Aug 05 '12 at 08:07

2 Answers2

2

The functions don't exist unless the module executes. You can't have it both ways. Perhaps you need to add a main stanza to the module.

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • ok, so I think I know what to do with a main stanza. Please check the edit (if you don't see it I will add it in a second) in the main post, just bceause I can not format it correctly in a comment – bs7280 Aug 05 '12 at 07:45
0

The problem is, that you get the actions module returned. Try this:

mymodule = __import__('actions.'+filename)
for submodule in filename.split('.'):
    mymodule = getattr(mymodule, submodule)

This happens when you try importing a submodule, i.e. module.something.somethingelse, you get module returned.

phant0m
  • 16,595
  • 5
  • 50
  • 82
  • actions is a folder, when I tried using the "/" character I got syntax error problems. – bs7280 Aug 05 '12 at 08:39
  • @user1270285 Yes, I'm aware it is a folder. That's how Python modules work. `/` denotes division. Have you tried whether it works? – phant0m Aug 05 '12 at 08:45
  • AttributeError: 'module' object has no attribute 'OpenEmail' – bs7280 Aug 06 '12 at 06:09
  • @user1270285: Is `OpenMail` the name of your package, or just the name of a function? Can you update the post with your folder/file structure and what `filename` is when you invoke the code? – phant0m Aug 06 '12 at 07:17