简体   繁体   中英

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

Start with:

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

Then forget about sys.argv and only use args .

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))

您可以从1(range(1,len(sys.argv))开始

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM