Search code examples
pythongetopt

python getopt error : "option --ip not recognized" from ipykernel_launcher


When I am running my python in vs code with ipython, I get error:

option --ip not recognized

it seems run with some default options, but impacts to my getopt function with bellow code:

#%%
opts, args = getopt.getopt(sys.argv[1:],"hs:v:m",["symbol=","vendor="])
for o, a in opts:
    if o == "-s":
        sym = a
    elif o == "-v":
        data_vendor = a
    elif o == "-m":
        massive_testing = True
    else:
        pass

I tried my debug code:

#%%
print(sys.argv)

I get bellow:

['/usr/lib/python3/dist-packages/ipykernel_launcher.py', '--ip=127.0.0.1', '--stdin=9028', '--control=9026', '--hb=9025', '--Session.signature_scheme="hmac-sha256"', '--Session.key=b"a6676a2b-4cfa-4056-a571-5b5c95b0f3f1"', '--shell=9027', '--transport="tcp"', '--iopub=9029', '--f=/tmp/tmp-477906pu3LAf814T5H.json']

I don't want parse these system options, it there anyway work round?


Solution

  • Yes, you can opt those out if you know your needed options beforehand

    NOTE: I am using 4 spaces as indentation here , python might give you error with invalid indentation

    for those whose are in hurry , you can copy this codes as template and without many comment

    toptions = [] #add short options
    long_options = []  #add long options  
    unrecognisedlist = []  #for recognised options
    recognised = []  #for unrecognised optoins
    for arg in sys.argv[1:] :recognised.append(arg) if arg.strip('--') in long_options else unrecognisedlist.append(arg)
    
    try:
        arguments, values = getopt.getopt(recognised, toptions, long_options)`
               #<your codes with arguments and values>
    except Exceptions as e:
         print(e)
    

    As an Example Try this,

     #adding needed option to a list for easiness , you can omit '='
     # I have added it like ,
     # long_options =["help","no-reset","no-run","printErrors"]
     #Note: my long_options are considered boolean 
     #so if it exists in arg it is considered as True or False
    
    toptions = "" #ignoring short codes in this,as the question is for long options
    long_options =["help","no-reset","no-run","printErrors"] #as for thequestion["symbol=","vendor="]  
     #creating list variables to store values  
    unrecognisedlist = []
    recognised = []
     # looping over sys arg, I will explain it below
    for arg in sys.argv[1:] :recognised.append(arg) if arg.strip('--') in long_options else unrecognisedlist.append(arg)
    
    #best practice: show there are unrecognised options to the user
    #<any error handling code for unrecognised>
    print("these options are unrecognised",unrecognisedlist)
    try:
        # Parsing only recognized arguments
        arguments, values = getopt.getopt(recognised, toptions, long_options)`
    
               #<your codes with arguments and values>
               #Such as,
        for currentArgument, currentValue in arguments:
            print("checking for arguments") 
         #including short options for reference  
            if currentArgument in ("-h", "--help"):
                print ("Displaying Help")
                print(" -n , --no-reset : will not reset last session of the app , useful to skip certain login scenarios")
                print ('"-r", "--no-run"',"testcases will not execute only evaluate")                no_run = True
    
            elif currentArgument in ("-n", "--no-reset"):
                print ("no reset turned on. App will not reset in each execution")
                noreset = True
             
            elif currentArgument in ("-r", "--no-run"):
    
                print (("testcases will not execute with no run option :: (% s) ::") % (currentValue))
                no_run = True
    
            elif currentArgument in ("-e","--printErrors"):
                print("opening file changes.txt , system will exit after print")
                print("text case run disabled")
                no_run = True
                with open('changes.txt') as file_object:
                    for line in file_object:
                        print(line,"", end='')
                sys.exit("\n\nCHANGES AND ERRORS are printed IN changes.txt now exiting\n\n")
    
    except Exceptions as e:
         print(e)
    

    Now I will break down the iteration logic for you,

    #the one liner

    for arg in sys.argv[1:] :recognised.append(arg) if arg.strip('--') in long_options else unrecognisedlist.append(arg)
    

    is same as

    for arg in sys.argv[1:] :
        recognised.append(arg) if arg.strip('--') in long_options else unrecognisedlist.append(arg)
    

    or more elaborately

    for arg in sys.argv[1:] :
        if arg.strip('--') in long_options:
             recognised.append(arg)
        else:
             unrecognisedlist.append(arg)
    

    since we get all the passed arguments in "sys.argv[1:] ", we will iterate over each and append it to the appropriate list variables.

    we need to strip the arg with arg.strip('--') because the sys.argv[1:] returns those with "--" prefixed string exactly like we are passing it through options, Then we check each with that in long_option , if a match found -append it to recognised and else unrecognisedlist