Passing argument to function from command line

My son wrote a command line program in ruby for me. I want to convert it to python. To run the program he has done this on the command line; “./myProgram.rb ‘argument’”. Then the 'argument ’ is passed into the program to be processed. I want to do the same in python. I am not asking that someone write the code for me, rather give me a hint where I can get the info to do that. Oh yes, I am sort of a nub when it comes to programming.

Depending on the complexity of your program, you’re likely looking for either sys.argv (a list of all of the command-line arguments as strings) or argparse (a module in the standard library for building user friendly command-line interfaces).

One of the following templates may help you get started:

#!/usr/bin/env python3

import sys

def print_uppercase(s):
    print(f"uppercase: {s.upper()}")

if len(sys.argv) < 2:
    print("too few arguments")
    sys.exit(1)
print_uppercase(sys.argv[1])
#!/usr/bin/env python3

import argparse

def print_uppercase(s):
    print(f"uppercase: {s.upper()}")

parser = argparse.ArgumentParser()
parser.add_argument("my_argument")
args = parser.parse_args()

print_uppercase(args.my_argument)

Hello,

so you want to run the Python script from the command line including passing arguments:

This tutorial should be what you are looking for:

Thanks everyone, that looks as though it will get me started down the right path.

Mel…

Let me add this. In his ruby script he used ‘ARGV’ so that looks familiar. The script is small. It is used to read lines from a data file and any line that contains the argument is printed to std out. The data file is just a list of family birthdays so the argument will be a month. I am going to have it print to a file on my desktop so I can see who has birthdays that month. Not very earth shattering!

Mel…

Yes, likely the sys.argv approach is best because your needs are simple. You have to run import sys first and then sys.argv is a Python list that contains the strings of the script filename and any arguments after it.

OK, looking for opinions here. What Python reference book do you have close at hand?

Mel…

The official documentation, particularly the library reference.

Thanks ND. Have bookmarked it and will use it I’m sure. I have the program working though I changed it some what from my original idea. Now you don’t have to put the month on the command line. I used “datetime” to get the month and have months set up in a dictionary. Also writing the output to a file on desktop.