简体   繁体   中英

In Jupyter, how do you tell which browser you are in?

In my Jupyter notebook, I need to know whether I am running in Chrome or Firefox because the code to save a figure in Altair is different depending on the browser ( https://altair-viz.github.io/user_guide/saving_charts.html ).

How can I do this?

The Jupyter kernel (ie Python backend) has no direct information about the frontend that is connected to it. But you can use system tools to try to infer what browser processes are running. For example, the psutil module allows you to list running processes. I have a Chrome and Safari browsers open currently, and I get these results:

>>> import psutil
>>> 'Google Chrome' in (p.name() for p in psutil.process_iter())            
True
>>> 'Firefox' in (p.name() for p in psutil.process_iter())                  
False
>>> 'Safari' in (p.name() for p in psutil.process_iter())                   
True

Some caveats:

  • the process name might vary from operating system to operating system: I would check on that if it's important to work consistently across platforms.
  • this does not tell you whether the user is using this particular frontend for viewing the Jupyter notebook, but whether the process of that name is running at all.
  • For saving altair charts, note that the browser alone is not enough: you'll also need the user to have chromedriver installed for Chrome, or geckodriver installed for Firefox. It may be better to detect whether those drivers are installed rather than detecting the currently running browser. See Saving Charts for more information.

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