Search code examples
pythoncmdparametersargumentssystem

Python, argument parameter error with sys module


I am trying to get arguments in python with the sys module. Here my code:

import sys
import os
path = sys.argv[0]
argument = sys.argv[1]
print("Hello, Temal Script installed.")
if argument == "-h":
    os.system("cls")
    print("Available comamnds:\n-h = help\n-i = information\n-v = version")
if argument == "-i":
    os.system("cls")
    print("This is a script written by Temal")
if argument == "-v":
    os.system("cls")
    print("Version: 1.0")

If I enter in the cmd "main.py -h" it works great. But if I enter only "main.py" it prints me out an error:

Traceback (most recent call last):
  File "C:\Windows\cmd.py", line 5, in <module>
    argument = sys.argv[1]
IndexError: list index out of range

I know why i get this error, because in the list will be only one item (the path) because i dont enter a second argument. But how can I do that the script ignores this error if no second argument is set? If someone enters main.py without an argument I only want to print out this text: Hello, Temal Script installed. Or maybe is there something like in PHP "isset"? I am also new to this topic so please answer simple and not complicated. Thanks!


Solution

  • Need to check the length of the sys.argv variable.

    import sys
    import os
    
    path = sys.argv[0]
    if len(sys.argv) > 1:
        argument = sys.argv[1]
        print("Hello, Temal Script installed.")
        if argument == "-h":
            os.system("cls")
            print("Available comamnds:\n-h = help\n-i = information\n-v = version")
        elif argument == "-i":
           os.system("cls")
           print("This is a script written by Temal")
        elif argument == "-v":
            os.system("cls")
            print("Version: 1.0")
    

    Also, look at argparse module.

    import argparse
    import os
    
    parser = argparse.ArgumentParser(description="My App")
    parser.add_argument('-i', '--info', action='store_true',
        help="show information")
    parser.add_argument('-v', '--version', action='store_true',
        help="show version")
    args = parser.parse_args()
    
    if args.info:
        os.system("cls")
        print("This is a script written by Temal")
    elif args.version:
        os.system("cls")
        print("Version: 1.0")
    

    Run main.py -h outputs:

    usage: help.py [-h] [-i] [-v]
    
    My App
    
    optional arguments:
      -h, --help     show this help message and exit
      -i, --info     show information
      -v, --version  show version