在Python中调用外部函数

0 投票
8 回答
11927 浏览
提问于 2025-04-15 17:10

我想在一个条件判断里,从另一个文件里调用(执行)一个函数。我听说返回语句是行不通的,所以我希望有人能告诉我,应该用什么语句才能调用外部的函数。

这个函数会创建一个沙盒,但如果沙盒已经存在,我想跳过这个条件判断。

这是我用的一个小代码片段。

import mks_function  
from mksfunction import mks_create_sandbox  
import sys, os, time  
import os.path  

if not os.path.exists('home/build/test/new_sandbox/project.pj'):
 return mks_create_sandbox()  
else:  
 print pass  

8 个回答

2

最近我在做我的Python期末项目时,对这个问题有了很深的理解。我也很想看看你外部函数的文件。

如果你要调用一个模块(其实,任何在不同文件里的函数都可以看作一个模块,我不喜欢说得太死),你需要确保一些事情。这里有一个模块的例子,我们叫它 my_module.py。

# Example python module

import sys
# Any other imports... imports should always be first

# Some classes, functions, whatever...
# This is your meat and potatos

# Now we'll define a main function
def main():
    # This is the code that runs when you are running this module alone
    print sys.platform

# This checks whether this file is being run as the main script
#  or if its being run from another script
if __name__ == '__main__':
    main()
# Another script running this script (ie, in an import) would use it's own
#  filename as the value of __name__

现在我想在另一个文件中调用这个完整的函数,那个文件叫做 work.py。

import my_module

x = my_module
x.main()
5

假设你的函数 bar 在一个叫做 foo.py 的文件里,并且这个文件在你的 Python 路径中。

如果 foo.py 里面有这些内容:

def bar():
  return True

那么你可以这样做:

from foo import bar

if bar():
  print "bar() is True!"
2

让我们看看文档是怎么说的

return 只能在函数定义里面使用,不能在嵌套的类定义中使用。

我猜你想做的是:

from mksfunction import mks_create_sandbox  
import os.path

if not os.path.exists('home/build/test/new_sandbox/project.pj'):
    mks_create_sandbox()

撰写回答