Running external module and accessing the created objects

Rick Johnson rantingrickjohnson at gmail.com
Tue Mar 12 02:40:48 EDT 2013


On Monday, March 11, 2013 6:57:28 PM UTC-5, Kene Meniru wrote:
>
> ------------------------------------------
> # 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

Hmm. I don't understand why you think a simple old import won't work. Here is code (with names slightly adjusted for sanity).

============================================================
 Contents of "mymodule.py"
============================================================

import math

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
        self.name = "MyAppName"

def foo():
    boke = "Smilling"
    print math.sin(1), boke

============================================================
 Contents of "myscript.py"
============================================================

# This next import statement requires that a script named
# "myapp.py" exist on the Python search path. If you cannot
# bring the script into the search path, you can bring the
# search path to the script by editing "sys.path".
#
# import sys
# sys.path.append('foderContainingMyModule')
# del sys
#
# But i would suggest placing the module on search path.

from mymodule import Foo, foo

def test():
##    dic = {}
##    execfile("myapp.py", dic)
##    testObj = dic["MyApp"]() # access MyApp class
    instance = Foo()
##    dic["testFunction"]()    # execute testFunction
    foo()
##    print testObj.name       # print string
    print instance.name

if __name__ == '__main__':
    test()

============================================================
 Results of running "myscript"
============================================================

0.841470984808 Smilling
MyAppName




More information about the Python-list mailing list