4

I have written a little Python script that checks for arguments and prints them if enough arguments or warnings if not enough or no arguments. But by default, the script itself is one of the arguments and I do not want to include it in my code actions.

import sys

# print warning if no arguments.
if len(sys.argv) < 2: 
  print("\nYou didn't give arguments!")
  sys.exit(0)

# print warning if not enough arguments.
if len(sys.argv) < 3: 
  print("\nNot enough arguments!")
  sys.exit(0)

print("\nYou gave arguments:", end=" ")
# print arguments without script's name
for i in range(0, len(sys.argv)):
  if sys.argv[i] == sys.argv[0]: # skip sys.argv[0]
    continue
  print(sys.argv[i], end=" ") # print arguments next to each other.

print("")

I have solved this with:

if sys.argv[i] == sys.argv[0]: # skip sys.argv[0]
    continue

But is there a better/more proper way to ignore the argv[0]?

K4R1
  • 745
  • 1
  • 10
  • 20
  • You could just change it to `for i in range(1, len(sys.argv))` to skip the 0th element. – Blorgbeard Apr 12 '19 at 22:09
  • "Why?" -- so programs can change their behavior based on how they're called. It's like how `vim`, `view` and `vimdiff` are all the same command (hardlinks to the same executable), but it has three different behaviors when called under each name. Or how `busybox` can be hundreds of UNIX commands with only one executable. – Charles Duffy Apr 12 '19 at 22:10
  • ...so, yeah, that part of the question is duplicative with [Why is argv (argument vector) in C defined as a pointer and what is the need for defining its zeroth as the program name?](https://stackoverflow.com/questions/21732633/why-is-argv-argument-vector-in-c-defined-as-a-pointer-and-what-is-the-need-for); I've edited it out so the question is strictly on-topic and non-duplicative. – Charles Duffy Apr 12 '19 at 22:13
  • 1
    Your solution would skip arguments that happen to be the same as your script name. – chepner Apr 12 '19 at 22:13

3 Answers3

10

Start with:

args = sys.argv[1:]   # take everything from index 1 onwards

Then forget about sys.argv and only use args.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
1

Use argparse to process the command-line arguments.

import argparse


p = argparse.ArgumentParser()
p.add_argument("args", nargs='+')
args = p.parse_args()

print("You gave arguments" + ' '.join(args.args))
chepner
  • 497,756
  • 71
  • 530
  • 681
1

You can start from 1 (range(1, len(sys.argv)))