Running external module and accessing the created objects

Dave Angel davea at davea.name
Tue Mar 12 01:48:43 CET 2013


On 03/11/2013 07:57 PM, Kene Meniru wrote:
> Here's the answer to this question.
>
> The summary of the question: how to run a module (called myapp.py) from
> another module (called myappwin.py) and be able to access the namespace of
> myapp.py from myappwin.py.
>
> ------------------------------------------
> # contents of myapp.py
> import math
>
> class MyApp(object):
>      def __init__(self):
>          super(MyApp, self).__init__()
>          self.name = "MyAppName"
>
>
> def testFunction():
>      boke = "Smilling"
>      print math.sin(1), boke
> -----------------------------------------
> # contents of myappwin
> def test():
>      dic = {}
>      execfile("myapp.py", dic)
>      testObj = dic["MyApp"]() # access MyApp class
>      dic["testFunction"]()    # execute testFunction
>      print testObj.name       # print string
>
>
> test()
> -----------------------------------------
> # OUTPUT
> $ python myappwin.py
> 0.841470984808 Smilling
> MyAppName
>

I hope you're just kidding.  execfile() and exec() are two of the most 
dangerous mechanisms around.  import or __import__() would be much 
better, as long as your user hasn't already run myapp.py as his script.


-- 
DaveA



More information about the Python-list mailing list