Amal Ts
Amal Ts

Reputation: 861

Import/execute a module and call function from parent module

I'm trying to call an external python script from my django app. I want to call a function from the parent module in the external python script. I tried the following ways.

  1. Using subprocess.call : In this case, i'm not able to use the functions from the parent file. The target function uses Django models to do some db operations.

  2. Import external file : I tried importing the external file using import(), but i cannot access the functions defined in the parent module.

Sample code :

from app.models import x

def save():
    print x.objects.all()    

def do_stuff():
    subprocess.call('external_script')


#----------External script --------
''' some code here '''

#Calling save function from parent 
save()

How do i achieve this?

Upvotes: 6

Views: 7800

Answers (2)

GwynBleidD
GwynBleidD

Reputation: 20569

If you have access to edit that external module and you're calling some function from it, not just importing that, you can pass an callback from first module:

def save():
    pass # do something here

def execute_external_module():

    from external_module import some_function
    some_function(save)

def some_function(callback=None):
    # do something here

    if callback is not None:
        callback()

Upvotes: 5

Huazuo Gao
Huazuo Gao

Reputation: 1733

A module knows nothing of where it is imported, specifically, a module's global is freshly created when it is imported. Thus if the importer is not cooperative, an imported module can never touch an object that lives in importer's namespace. If a module needs to call a function in parent's namespace, its parent must pass that function to the module. Concretely:

#child
def do_stuff(parents_function):
    pass

#parent
def func():
    pass

import child
child.do_stuff(func)

However, modules are not perfectly isolated, due to the cache. Therefore, if you know the name of parent module, you can do this:

#child
import parent
def do_stuff():
    parent.func()

#parent
import child
def func():
    pass
child.do_stuff()

Upvotes: 3

Related Questions