Ubuntu – How to pass arguments to functions while executing a python script from terminal

command linefunctionspython

I have a python file named solution.py and I can successfully execute it through the terminal using the following commands:

chmod +x solution.py
python3 solution.py

This works just fine if I have simple print phrases and so on.

What should I do if I have defined a function in solution.py and I want to call it with parameters that I want directly from terminal? How do I pass the arguments to the function call?

Best Answer

You can also use the sys module. Here is an example :

import sys

first_arg = sys.argv[1]
second_arg = sys.argv[2]

def greetings(word1=first_arg, word2=second_arg):
    print("{} {}".format(word1, word2))

if __name__ == "__main__":
    greetings()
    greetings("Bonjour", "monde")

It has the behavior your are looking for :

$ python parse_args.py Hello world
Hello world
Bonjour monde