[英]Running a python method/function directly from a file
我想知道是否有一種方法可以直接從文件中直接運行python函數,只需在一行中提及文件后跟函數。
例如,假設我有一個帶有' newfunction() '函數的文件' test.py '。
---------- ----------- test.py
def newfunction():
print 'welcome'
我可以運行newfunction()做類似的事情。
python test.py newfunction
我知道如何導入和調用函數等。在django等( 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))
結果:
➜ 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
我想你應該看看:
https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/
所有這些命令,如migrate
, runserver
或dbshell
等都像在該鏈接中描述的那樣實現:
應用程序可以使用manage.py注冊自己的操作。 為此,只需將管理/命令目錄添加到應用程序即可。
Django將為該目錄中的每個Python模塊注冊一個manage.py命令,該模塊的名稱不以下划線開頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.