Running python method / function directly from file

I would like to know if there is a way to directly run a python function directly from a file, just by mentioning the file name followed by the function on one line.

For example, let's say I have a test.py 'file with the newfunction () function.

---------- test.py -----------

def newfunction(): print 'welcome' 

Can I run the newfunction () function to do something like this.

  python test.py newfunction 

I know how to import and call functions, etc. If you saw similar commands in django etc. ( python manage.py runserver ), I felt that there was a way to directly call such a function. Let me know if something like this is possible.

I want to use it with django. But the answer that applies everywhere would be great.

+5
source share
2 answers

Try with globals() and 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)) 

Results:

 ➜ 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 
+4
source

I think you should take a look at:

https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/

All commands like migrate , runserver or dbshell , etc. implemented as described in this link:

Applications can log their actions with manage.py . To do this, simply add the management / commands directory to the application.

Django will register the manage.py command for each Python module in this directory whose name does not begin with an underscore.

+1
source

Source: https://habr.com/ru/post/1247329/


All Articles