James Mchugh
James Mchugh

Reputation: 1014

Running Python code without arguments when arguments are expected

I am trying to write a python code that will be executed in a shell with arguments such as:

python programName.py arg1 arg2

I have to write the code so that if no arguments are passed it will default to default values that are declared in the code. I tried doing this by using something similar to:

# ... Imports such as sys
x = argv[0]
y = argv[1]
#  ... Other Code

def main():
 if x is None:
  x = 0
 if y is None:
  y = 12
# ... Other Code

But Python did not like my way of doing it, and it would throw an error when no arguments are passed.

Sorry I can't show the error because the program is on my other computer that is not with me. What would be the proper way to do this?

Upvotes: 0

Views: 663

Answers (3)

Vijay Kumar
Vijay Kumar

Reputation: 191

How about doing the following. You need to check the length of the argument list to determine, the no. of arguments passed.

import sys

x = None
y = None

if len(sys.argv) > 3:
   print("Usage: ....")
   sys.exit(1)

if len(sys.argv) > 1:
   x = sys.argv[1]

if len(sys.argv) > 2:
   y = sys.argv[2]

Upvotes: 0

Akhil Thayyil
Akhil Thayyil

Reputation: 9403

Try this:

import sys

# ... Imports such as sys
x = sys.argv[1] if len(sys.argv) > 1 else None  # None is the default value
y = sys.argv[2] if len(sys.argv) > 2 else None  # None is the default value
#  ... Other Code

sys.argv[0] -> gives the program file name

In the above question you're running python program_file_name x y, in this case sys.argv[0] gives you the program_file_name.

Upvotes: 2

Klaus D.
Klaus D.

Reputation: 14369

You should check the length of argv:

if len(argv) < 2:
    x = 0
if len(argv) < 3:
    y = 12

Upvotes: 0

Related Questions