pythonwindowspython-webbrowser

Python start browser with current user directory on Windows


I want to open web browser with url my python script.

I have a more than 100+ user. I want to run the my python script with every user desktop portable chrome for ex. C:\Users\user1\Desktop\chrome\chrome.exe

My code; import webbrowser import os url = 'http://example.com/' webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(r"C:\Users\**user1**\Desktop\chrome\chrome.exe")) webbrowser.get('chrome').open(url)

I want the name of the user running the python file in the user part . Each user's desktop has the same exe file in the same folder. Single variable user part ex. C:\Users\user1, C:\Users\user2\ ...

Thanks for helping.

When user10 starts the python file, open the browser with portable chrome in the chrome folder on user10's desktop.


Solution

  • Try the following solution, all it does, is simply using os.getlogin() function which returns the username of the current user and assign it to username variable, then the username variable is being used as part of the path.

    import webbrowser
    import os
    
    username = os.getlogin()
    url = 'http://example.com/'
    webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(f'C:\\Users\\{username}\\Desktop\\chrome\\chrome.exe'))
    webbrowser.get('chrome').open(url)```