在python中调用外部函数

2024-05-17 07:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从if语句中的另一个文件返回(执行)函数。 我读到return语句不起作用,我希望有人知道什么语句允许我调用外部函数。

函数创建一个沙盒,但如果存在,我想传递if语句。

这是我使用的一小段代码。

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  

Tags: 文件path函数代码fromimport沙盒return
3条回答

让我们看看what docs say

return may only occur syntactically nested in a function definition, not within a nested class definition.

我想你想做的是:

from mksfunction import mks_create_sandbox  
import os.path

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

假设函数bar位于Python路径上名为foo.py的文件中。

如果foo.py包含以下内容:

def bar():
  return True

然后你可以这样做:

from foo import bar

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

最近,当我在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()

相关问题 更多 >