BigEfromDaBX
BigEfromDaBX

Reputation: 177

Passing an argument from terminal to python file

So i have a file named:

helloName.py

It has the following code below:

def hello(name,age):
print('Hello ' + name + '. How are you today?' )
print ('You are', age ,'years old.'  )

from terminal I would like to type helloName.py eric, 35 to run the script.

The result should be:

Hello Eric. How are you today?
You are 35 years old.

When I do it now it does nothing. No error or anything.

Upvotes: 2

Views: 302

Answers (1)

Govinda Malavipathirana
Govinda Malavipathirana

Reputation: 1141

You need to get input first and execute function after that. Edit your file like below...

import sys
def hello(name,age):
    print('Hello ' + name + '. How are you today?' )
    print ('You are', age ,'years old.'  )

name = sys.argv[1]
age = sys.argv[2]

hello(name, age)

Then type in terminal python3 <file_name>.py arg1 arg2. Arguments are arg1=Name and arg2=Age

Upvotes: 2

Related Questions