0

I'm fairly confused as to the proper implementation of command line arguments in a program. I've looked around and am confused whether or not a for loop is necessary. I know for sure that there will always be only two arguments passed to this program. Ultimately, is a for loop necessary in this situation? Here's the code in the main function:

def main():
try:
    if len(sys.argv) > 1:
        filename = sys.argv[1]
        length = int(sys.argv[2])
    wordDict = readFile(filename)
except IOError:
    print("Error: file not found.")

Thank you all for your input!

2 Answers 2

2

You do not need to use a loop if you know exactly how many arguments you want.

I have noticed that in your code that you check the number of sys.argv is greater than 1, you need to check that it is greater than 2 as the first sys.argv (sys.argv[0]) is the name script that you are running https://docs.python.org/3/library/sys.html?highlight=sys.argv#sys.argv

If only one argument is passed to your program it will currently result in an IndexError.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, if len(sys.argv) is less than 2, it will raise a NameError.
2

you can try argparse: https://docs.python.org/2/library/argparse.html

import argparse


parser = argparse.ArgumentParser(description='What ever the purpose of the script is')

parser.add_argument('filename', type=str,
                   help='path to the file')

parser.add_argument('length', type=int,
                   help='some length')

args = parser.parse_args()
print args.filename
print args.length

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.