How to create a function in python to be used from the terminal



To write a python code able to read variables or inputs from the command line you only have to use sys.argv. Let's see a couple of examples.

You can find the code here.


File called example_v1.py:

import sys
def main():  
    print sys.argv
    
if (__name__ == "__main__"):  

    main();


Then you go to the folder where you have it and run this comman in the comman line:


python example_v1.py

Like here:
As you can see the output is the name of the file.

Let's try this:


python example_v1.py  hi hola ciao


Basically the comand sys.argv is giving us a list of the commandline arguments received.


Now I am going to create a program that is going to say hi and the name that you introduce after file name in the commandline. I called this script example_v2.py:

import sys
def main():  
    print 'Hi ' + sys.argv[1] + '!'
    
if (__name__ == "__main__"):  

    main();

So now we can write in the terminal:


python example_v2.py  Eduard

This is the result:



References:

  • This tutorial is largely inspired in https://www.youtube.com/watch?v=DCxYAYzTWOI&t=677s.
  • To see sys.argv: http://www.pythonforbeginners.com/argv/more-fun-with-sys-argv 


Comentarios

Entradas populares de este blog

Making MongoDB remotely available.

Reflecting about SIR models and some examples

Adicction and Decision Making: a brainy view.