导入/执行一个模块并从父模块调用函数

5
我正在尝试从我的Django应用程序中调用外部Python脚本。我想要调用外部Python脚本中的父模块中的函数。我尝试了以下方法:
  1. 使用subprocess.call:在这种情况下,我无法使用来自父文件的函数。目标函数使用Django模型执行一些数据库操作。
  2. 导入外部文件:我尝试使用import()导入外部文件,但无法访问在父模块中定义的函数。
示例代码:
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()

我该如何实现这个?

1
对你来说,“从父模块调用函数”是什么意思?在该脚本中是否导入了某个模块?或者它是一个子模块,你正在尝试访问包含该子模块的模块? - GwynBleidD
你是说你在 app.models 中有一个保存方法,现在想要调用它? - idjaw
在给定的代码中,我从第一个程序调用外部脚本,该外部脚本需要访问第一个程序中定义的函数 - 在这种情况下是save()函数。@GwynBleidD - Amal Ts
@idjaw 不,save方法是使用Django模型之一。 - Amal Ts
2个回答

5
如果您可以编辑外部模块并从中调用某些函数,而不仅仅是导入它,那么您可以从第一个模块传递回调函数:
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()


2
一个模块不知道自己被导入到哪里,也就是说,当一个模块被导入时,它的全局变量会被重新创建。因此,如果导入者不合作,导入的模块永远无法接触到存在于导入者命名空间中的对象。如果一个模块需要调用父级命名空间中的函数,那么它的父级必须将该函数传递给该模块。具体而言:
#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()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接