Search code examples
pythonargvsys

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


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


Solution

  • Start with:

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

    Then forget about sys.argv and only use args.