在Python中调用外部函数
我想从if语句中的另一个文件返回(执行)一个函数。 我读过return语句不起作用,我希望有人知道什么声明可以让我调用外部函数。在Python中调用外部函数
该函数创建一个沙箱,但如果存在,我想通过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
让我们来看看what docs say:
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()
请注意,else:pass部分不是必需的。 – Brian 2009-12-18 15:36:36
-1:'else:pass' – 2009-12-18 15:42:15
'pass'是代码的占位符。 – SilentGhost 2009-12-18 16:09:46
您可能需要import
包含该功能的模块,否?
当然,对于你要达到的目标而言,精确度会有所帮助。
说你的函数bar
位于Python路径中的一个名为foo.py的文件中。
如果foo.py包含此:
def bar():
return True
然后,你可以这样做:
from foo import bar
if bar():
print "bar() is True!"
究竟你 “return语句将无法正常工作” 是什么意思?
您可以从另一个文件import
函数并将其称为本地函数。
这取决于你的意思。如果你想创建一个静态方法,那么你会做这样的事情
class fubar(object):
@classmethod
def foo():
return bar
fubar.foo() # returns bar
如果你想运行一个外部程序,那么你会用subprocess库并做
import subprocess
subprocess.popen("cmd echo 'test'",shell=true)
真的取决于你想要什么做
你的意思是import
?说,你的外部函数住在同一个目录mymodule.py,你必须先导入它:
import mymodule
# or
from mymodule import myfunction
然后是直截了当地使用功能:
if mymodule.myfunction() == "abc":
# do something
或与第二进口:
if myfunction() == "abc":
# do something
请参阅this tutorial。
file1.py(注释掉版本2)
#version 1
from file2 import outsidefunction
print (outsidefunction(3))
#version 2
import file2
print (file2.outsidefunction(3))
#version 3
from file2 import *
print (outsidefunction(3))
文件2。PY
def outsidefunction(num):
return num * 2
命令行:python file1.py
我对此有很大的触摸最近,因为我是工作在我的蟒蛇最后的项目。我也会参与查看你的外部函数文件。
如果你正在调用一个模块(实际上,同一个文件之外的任何函数都可以当作一个模块来处理,我讨厌把它指定得太精确),所以你需要确定一些东西。这里是一个模块的例子,让我们把它叫做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()
请澄清 - 是什么情况你在?向我们展示一些代码 – 2009-12-18 15:05:14
对于初学者来说,它并不完全清楚你想做什么 - 你想返回一个在外部文件中定义的函数,返回执行该外部函数返回的值,还是执行外部函数?如何处理一些示例代码? – 2009-12-18 15:05:24
你用这段代码得到了什么错误? – 2009-12-18 15:13:49