繁体   English   中英

直接从文件运行python方法/函数

[英]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/

所有这些命令,如migraterunserverdbshell等都像在该链接中描述的那样实现:

应用程序可以使用manage.py注册自己的操作。 为此,只需将管理/命令目录添加到应用程序即可。

Django将为该目录中的每个Python模块注册一个manage.py命令,该模块的名称不以下划线开头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM