我想知道是否有一种方法可以直接从文件中直接运行python函数,只需在一行中提及文件后跟函数.
例如,假设我有一个带有' newfunction() ' 函数的文件' test.py '.
---------- ----------- test.py
def newfunction():
print 'welcome'
Run Code Online (Sandbox Code Playgroud)
我可以运行newfunction()做类似的事情.
python test.py newfunction
Run Code Online (Sandbox Code Playgroud)
我知道如何导入和调用函数等.在django etc(python manage.py runserver)中看到类似的命令,我觉得有一种方法可以直接调用这样的函数.如果可能的话,请告诉我.
我希望能够与django一起使用它.但是,适用于所有地方的答案都很棒.
尝试globals()和arguments (sys.argv):
#coding:utf-8
import sys
def moo():
print 'yewww! printing from "moo" function'
def foo():
print 'yeeey! printing from "foo" function'
try:
function = sys.argv[1]
globals()[function]()
except IndexError:
raise Exception("Please provide function name")
except KeyError:
raise Exception("Function {} hasn't been found".format(function))
Run Code Online (Sandbox Code Playgroud)
结果:
? python calling.py foo
yeeey! printing from "foo" function
? python calling.py moo
yewww! printing from "moo" function
? python calling.py something_else
Traceback (most recent call last):
File "calling.py", line 18, in <module>
raise Exception("Function {} hasn't been found".format(function))
Exception: Function something_else hasn't been found
? python calling.py
Traceback (most recent call last):
File "calling.py", line 16, in <module>
raise Exception("Please provide function name")
Exception: Please provide function name
Run Code Online (Sandbox Code Playgroud)