-1

I imported a module as below:

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

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

for the time being, I am not immediately concerned with whether or not the script executes when I add the line below (when the script is imported) as I will get around it using the if __name__ == "__main__" trick.

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 doesn't have that function even though it exists in the script.

mymodule.OpenEmail(n)

The function name does not really matter, because I have been able to get the script below to work on its own when I run it but when trying to import it in idle and executing the line above I get an error saying that the module does not have that function (or some very similar error). Anyways, the following code is an example script that I am using like a plugin. But my main point is that I am able to dynamically import and execute a script in python but now I would like to be able to send variables through to the file. If I can somehow get functions to work like above I am sure that It would solve my problem.

import webbrowser
def OpenEmail():
    handle = webbrowser.get()
    handle.open('http://gmail.google.com')
OpenEmail()
print "Your email has been opened"
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
bs7280
  • 1,074
  • 3
  • 18
  • 32
  • 1
    Why a new question? http://stackoverflow.com/questions/11814565/python-trouble-with-calling-functions-from-a-module – phant0m Aug 05 '12 at 08:54
  • because I did not get a clear answer that would work and, at that time I thought it was due to my lack of clear stating of my problem in the other post. – bs7280 Aug 06 '12 at 06:39
  • 1
    @user1270285: You can edit your previous question. – Mechanical snail Aug 06 '12 at 06:47

2 Answers2

2

As documented, using __import__() with a dotted name and no fromlist argument returns a reference to the topmost package. It is up to you to access the appropriate attributes to descend the package hierarchy, either with dot notation or with getattr().

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Very simply, this is what I did in IDLE

filename = 'actions.email'
mod = __import__(filename)
VAR = getattr(mod, 'email')
VAR.OpenEmail()

got my email to open!

bs7280
  • 1,074
  • 3
  • 18
  • 32