Search code examples
pythonif-statementpython-webbrowser

Why does Python seem to run the else statement although the if clause is true?


I tried to write a simple program in Python 3.10 that opens (at least) one browser window and can take input from the command line to open additional windows:

import webbrowser
import sys

if len(sys.argv) > 1:
    for a in range(len(sys.argv)):
        webbrowser.open(sys.argv[a])
else:
    webbrowser.open("www.google.com")

I run that from a one-line batchfile so I can enter additional websites to open. That does work well, however, it always opens Google, no matter if command line arguments are passed or not (if I just run it without arguments, it opens Google. If I run it with e.g. LinkedIn as an argument, it opens Google and LinkedIn. If I use wikipedia and LinkedIn as arguments, it opens both of these plus Google etc).

However what I want is that Google is only opened when no arguments are passed... The strange thing is that when I run the exact same code, but replace the webbrowser.open() with a print statement, it does exactly what it is supposed to do:

import sys

if len(sys.argv) > 1:
    for a in range(len(sys.argv)):
        print(sys.argv[a])
else:
    print("www.google.com")

Passing command line arguments to this code causes it to only print the arguments, "www.google.com" is only printed when no arguments are passed.

I am sorry, but I am completely lost why these two codes act differently. I address both by running a batch file that goes

@py.exe C:\Users\[Route to the file]\[File].py %*

What I have tried is replacing the else statement by elif len(sys.argv) == 1, but that acts exactly the same. The only differnce I see is the usage of the webbrowser module. Can importing a module change behaviour of the code in that way?

Thank you in advance!


Solution

  • argv captures the python script name and the website, which you already know because you're checing if len > 1. However you're then iterating over all args, causing the browser to attempt to load both the script name and the website as websites. Since the script name is not a valid url, I'm assuming your browser is opening to your default page, which happens to be google.com.

    You need to skip the first arg, which you can do by sys.arvg[1:]

    import webbrowser
    import sys
    
    if len(sys.argv) > 1:
        for a in sys.argv[1:]:
            webbrowser.open(a)
    else:
        webbrowser.open("www.google.com")