How can I skip sys.argv[0] when dealing with arguments?
Asked Answered
S

3

5

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]?

Server answered 12/4, 2019 at 22:7 Comment(4)
You could just change it to for i in range(1, len(sys.argv)) to skip the 0th element.Breastbeating
"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.Cryptozoite
...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?; I've edited it out so the question is strictly on-topic and non-duplicative.Cryptozoite
Your solution would skip arguments that happen to be the same as your script name.Phalanger
B
11

Start with:

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

Then forget about sys.argv and only use args.

Breastbeating answered 12/4, 2019 at 22:11 Comment(0)
P
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))
Phalanger answered 12/4, 2019 at 22:11 Comment(0)
G
1

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

Galateah answered 12/4, 2019 at 22:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.