├── .github
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ ├── feature_request.md
│ └── help-me.md
└── workflows
│ ├── codeql-analysis.yml
│ ├── main.yml
│ └── test.yml
├── .gitignore
├── .python-version
├── .travis.yml
├── CHANGELOG.md
├── LICENSE
├── MANIFEST.in
├── README-developers.md
├── README.md
├── eel
├── __init__.py
├── __main__.py
├── browsers.py
├── chrome.py
├── edge.py
├── eel.js
├── electron.py
├── msIE.py
├── py.typed
└── types.py
├── examples
├── 01 - hello_world-Edge
│ └── hello.py
├── 01 - hello_world
│ ├── hello.py
│ └── web
│ │ ├── favicon.ico
│ │ └── hello.html
├── 02 - callbacks
│ ├── callbacks.py
│ └── web
│ │ ├── callbacks.html
│ │ └── favicon.ico
├── 03 - sync_callbacks
│ ├── sync_callbacks.py
│ └── web
│ │ ├── favicon.ico
│ │ └── sync_callbacks.html
├── 04 - file_access
│ ├── README.md
│ ├── Screenshot.png
│ ├── file_access.py
│ └── web
│ │ ├── favicon.ico
│ │ └── file_access.html
├── 05 - input
│ ├── script.py
│ └── web
│ │ ├── favicon.ico
│ │ └── main.html
├── 06 - jinja_templates
│ ├── hello.py
│ └── web
│ │ ├── favicon.ico
│ │ └── templates
│ │ ├── base.html
│ │ ├── hello.html
│ │ └── page2.html
├── 07 - CreateReactApp
│ ├── .gitignore
│ ├── Demo.png
│ ├── README.md
│ ├── eel_CRA.py
│ ├── package-lock.json
│ ├── package.json
│ ├── public
│ │ ├── favicon.ico
│ │ ├── index.html
│ │ └── manifest.json
│ ├── src
│ │ ├── App.css
│ │ ├── App.test.tsx
│ │ ├── App.tsx
│ │ ├── index.css
│ │ ├── index.tsx
│ │ ├── logo.svg
│ │ ├── react-app-env.d.ts
│ │ └── serviceWorker.ts
│ └── tsconfig.json
├── 08 - disable_cache
│ ├── disable_cache.py
│ └── web
│ │ ├── disable_cache.html
│ │ ├── dont_cache_me.js
│ │ └── favicon.ico
├── 09 - Eelectron-quick-start
│ ├── .gitignore
│ ├── hello.py
│ ├── main.js
│ ├── package-lock.json
│ ├── package.json
│ └── web
│ │ ├── favicon.ico
│ │ └── hello.html
└── 10 - custom_app_routes
│ ├── custom_app.py
│ └── web
│ └── index.html
├── mypy.ini
├── requirements-meta.txt
├── requirements-test.txt
├── requirements.txt
├── setup.py
├── tests
├── conftest.py
├── data
│ └── init_test
│ │ ├── App.tsx
│ │ ├── hello.html
│ │ ├── minified.js
│ │ └── sample.html
├── integration
│ └── test_examples.py
├── unit
│ └── test_eel.py
└── utils.py
└── tox.ini
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: samuelhwilliams
2 | patreon: # Replace with a single Patreon username
3 | open_collective: # Replace with a single Open Collective username
4 | ko_fi: # Replace with a single Ko-fi username
5 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
6 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
7 | liberapay: # Replace with a single Liberapay username
8 | issuehunt: # Replace with a single IssueHunt username
9 | otechie: # Replace with a single Otechie username
10 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
11 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: bug
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Eel version**
11 | Please state the version of Eel you're using.
12 |
13 | **Describe the bug**
14 | A clear and concise description of what the bug is.
15 |
16 | **To Reproduce**
17 | Steps to reproduce the behavior:
18 | 1. Go to '...'
19 | 2. Click on '....'
20 | 3. Scroll down to '....'
21 | 4. See error
22 |
23 | **Expected behavior**
24 | A clear and concise description of what you expected to happen.
25 |
26 | **System Information**
27 | - OS: [e.g. Windows 10 x64, Linux Ubuntu, macOS 12]
28 | - Browser: [e.g. Chrome 108.0.5359.99 (Official Build) (64-bit), Safari 16, Firefox 107.0.1]
29 | - Python Distribution: [e.g. Python.org 3.9, Anaconda3 2021.11 3.9, ActivePython 3.9]
30 |
31 | **Screenshots**
32 | If applicable, add screenshots to help explain your problem.
33 |
34 | **Additional context**
35 | Add any other context about the problem here.
36 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: enhancement
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/help-me.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Help me
3 | about: Get help with Eel
4 | title: ''
5 | labels: help wanted
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the problem**
11 | A clear and concise description of what you're trying to accomplish, and where you're having difficulty.
12 |
13 | **Code snippet(s)**
14 | Here is some code that can be easily used to reproduce the problem or understand what I need help with.
15 |
16 | - [ ] I know that if I don't provide sample code that allows someone to quickly step into my shoes, I may not get the help I want or my issue may be closed.
17 |
18 | ```python
19 | import eel
20 |
21 | ...
22 | ```
23 |
24 | ```html
25 |
26 | ...
27 |
28 | ```
29 |
30 | **Desktop (please complete the following information):**
31 | - OS: [e.g. iOS]
32 | - Browser [e.g. chrome, safari]
33 | - Version [e.g. 22]
34 |
35 | **Smartphone (please complete the following information):**
36 | - Device: [e.g. iPhone6]
37 | - OS: [e.g. iOS8.1]
38 | - Browser [e.g. stock browser, safari]
39 | - Version [e.g. 22]
40 |
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | name: "CodeQL"
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | pull_request:
7 | # The branches below must be a subset of the branches above
8 | branches: [main]
9 | schedule:
10 | - cron: '0 11 * * 0'
11 |
12 | jobs:
13 | analyse:
14 | name: Analyse
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - name: Checkout repository
19 | uses: actions/checkout@v2
20 | with:
21 | # We must fetch at least the immediate parents so that if this is
22 | # a pull request then we can checkout the head.
23 | fetch-depth: 2
24 |
25 | # If this run was triggered by a pull request event, then checkout
26 | # the head of the pull request instead of the merge commit.
27 | - run: git checkout HEAD^2
28 | if: ${{ github.event_name == 'pull_request' }}
29 |
30 | # Initializes the CodeQL tools for scanning.
31 | - name: Initialize CodeQL
32 | uses: github/codeql-action/init@v1
33 | # Override language selection by uncommenting this and choosing your languages
34 | with:
35 | languages: javascript, python
36 |
37 | - name: Perform CodeQL Analysis
38 | uses: github/codeql-action/analyze@v1
39 |
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: Publish
2 |
3 | on:
4 | release:
5 | types: [published]
6 |
7 | jobs:
8 | build:
9 |
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | - name: Checkout repository
14 | uses: actions/checkout@master
15 | - name: Setup Python
16 | uses: actions/setup-python@master
17 | with:
18 | python-version: 3.x
19 | architecture: x64
20 | - name: Install setuptools
21 | run: pip install setuptools
22 | - name: Build a source distribution
23 | run: python setup.py sdist
24 | - name: Publish to prod PyPI
25 | uses: pypa/gh-action-pypi-publish@4f4304928fc886cd021893f6defb1bd53d0a1e5a
26 | with:
27 | user: __token__
28 | password: ${{ secrets.pypi_token }}
29 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test Eel
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | pull_request:
7 | # The branches below must be a subset of the branches above
8 | branches: [main]
9 | workflow_dispatch:
10 |
11 | jobs:
12 | test:
13 | strategy:
14 | fail-fast: false
15 | matrix:
16 | os: [ubuntu-20.04, windows-latest, macos-latest]
17 | python-version: [3.7, 3.8, 3.9, "3.10", "3.11", "3.12"]
18 | exclude:
19 | - os: macos-latest
20 | python-version: 3.7
21 |
22 | runs-on: ${{ matrix.os }}
23 |
24 | steps:
25 | - name: Checkout repository
26 | uses: actions/checkout@v2
27 | - name: Setup python
28 | uses: actions/setup-python@v2
29 | with:
30 | python-version: ${{ matrix.python-version }}
31 | - name: Setup test execution environment.
32 | run: pip3 install -r requirements-meta.txt
33 | - name: Run tox tests
34 | run: tox -- --durations=0 --timeout=240
35 |
36 | typecheck:
37 | strategy:
38 | matrix:
39 | os: [windows-latest]
40 |
41 | runs-on: ${{ matrix.os }}
42 |
43 | steps:
44 | - name: Checkout repository
45 | uses: actions/checkout@v2
46 | - name: Setup python
47 | uses: actions/setup-python@v2
48 | with:
49 | python-version: "3.x"
50 | - name: Setup test execution environment.
51 | run: pip3 install -r requirements-meta.txt
52 | - name: Run tox tests
53 | run: tox -e typecheck
54 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__
2 | dist
3 | build
4 | Drivers
5 | Eel.egg-info
6 | .tmp
7 | .DS_Store
8 | *.pyc
9 | *.swp
10 | venv/
11 | .tox
12 |
--------------------------------------------------------------------------------
/.python-version:
--------------------------------------------------------------------------------
1 | 3.10
2 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | cache: pip
3 | python:
4 | - 2.7
5 | - 3.6
6 | matrix:
7 | allow_failures:
8 | - python: 2.7
9 | install:
10 | #- pip install -r requirements.txt
11 | - pip install flake8 # pytest # add another testing frameworks later
12 | before_script:
13 | # stop the build if there are Python syntax errors or undefined names
14 | - flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics
15 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
16 | - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
17 | script:
18 | - true # pytest --capture=sys # add other tests here
19 | notifications:
20 | on_success: change
21 | on_failure: change # `always` will be the setting once code changes slow down
22 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change log
2 |
3 | ### 0.18.1
4 |
5 | * Fix: Include `typing_extensions` in install requirements.
6 |
7 | ### 0.18.0
8 | * Added support for MS Internet Explorer in #744.
9 | * Added supported for app_mode in the Edge browser in #744.
10 | * Improved type annotations in #683.
11 |
12 | ### 0.17.0
13 | * Adds support for Python 3.11 and Python 3.12
14 |
15 | ### v0.16.0
16 | * Drop support for Python versions below 3.7
17 |
18 | ### v0.15.3
19 | * Comprehensive type hints implement by @thatfloflo in https://github.com/python-eel/Eel/pull/577.
20 |
21 | ### v0.15.2
22 | * Adds `register_eel_routes` to handle applying Eel routes to non-Bottle custom app instances.
23 |
24 | ### v0.15.1
25 | * Bump bottle dependency from 0.12.13 to 0.12.20 to address the critical CVE-2022-31799 and moderate CVE-2020-28473.
26 |
27 | ### v0.15.0
28 | * Add `shutdown_delay` as a `start()` function parameter ([#529](https://github.com/python-eel/Eel/pull/529))
29 |
30 | ### v0.14.0
31 | * Change JS function name parsing to use PyParsing rather than regex, courtesy @KyleKing.
32 |
33 | ### v0.13.2
34 | * Add `default_path` start arg to define a default file to retrieve when hitting the root URL.
35 |
36 | ### v0.13.1
37 | * Shut down the Eel server less aggressively when websockets get closed (#337)
38 |
39 | ## v0.13.0
40 | * Drop support for Python versions below 3.6
41 | * Add `jinja2` as an extra for pip installation, e.g. `pip install eel[jinja2]`.
42 | * Bump dependencies in examples to dismiss github security notices. We probably want to set up a policy to ignore example dependencies as they shouldn't be considered a source of vulnerabilities.
43 | * Disable edge on non-Windows platforms until we implement proper support.
44 |
45 | ### v0.12.4
46 | * Return greenlet task from `spawn()` ([#300](https://github.com/samuelhwilliams/Eel/pull/300))
47 | * Set JS mimetype to reduce errors on Windows platform ([#289](https://github.com/samuelhwilliams/Eel/pull/289))
48 |
49 | ### v0.12.3
50 | * Search for Chromium on macOS.
51 |
52 | ### v0.12.2
53 | * Fix a bug that prevents using middleware via a custom Bottle.
54 |
55 | ### v0.12.1
56 | * Check that Chrome path is a file that exists on Windows before blindly returning it.
57 |
58 | ## v0.12.0
59 | * Allow users to override the amount of time Python will wait for Javascript functions running via Eel to run before bailing and returning None.
60 |
61 | ### v0.11.1
62 | * Fix the implementation of #203, allowing users to pass their own bottle instances into Eel.
63 |
64 | ## v0.11.0
65 | * Added support for `app` parameter to `eel.start`, which will override the bottle app instance used to run eel. This
66 | allows developers to apply any middleware they wish to before handing over to eel.
67 | * Disable page caching by default via new `disable_cache` parameter to `eel.start`.
68 | * Add support for listening on all network interfaces via new `all_interfaces` parameter to `eel.start`.
69 | * Support for Microsoft Edge
70 |
71 | ### v0.10.4
72 | * Fix PyPi project description.
73 |
74 | ### v0.10.3
75 | * Fix a bug that prevented using Eel without Jinja templating.
76 |
77 | ### v0.10.2
78 | * Only render templates from within the declared jinja template directory.
79 |
80 | ### v0.10.1
81 | * Avoid name collisions when using Electron, so jQuery etc work normally
82 |
83 | ## v0.10.0
84 | * Corrective version bump after new feature included in 0.9.13
85 | * Fix a bug with example 06 for Jinja templating; the `templates` kwarg to `eel.start` takes a filepath, not a bool.
86 |
87 | ### v0.9.13
88 | * Add support for Jinja templating.
89 |
90 | ### Earlier
91 | * No changelog notes for earlier versions.
92 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Chris Knott
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.md
--------------------------------------------------------------------------------
/README-developers.md:
--------------------------------------------------------------------------------
1 | # Eel Developers
2 |
3 | ## Setting up your environment
4 |
5 | In order to start developing with Eel you'll need to checkout the code, set up a development and testing environment, and check that everything is in order.
6 |
7 | ### Clone the repository
8 | ```bash
9 | git clone git@github.com:python-eel/Eel.git
10 | ```
11 |
12 | ### (Recommended) Create a virtual environment
13 | It's recommended that you use virtual environments for this project. Your process for setting up a virutal environment will vary depending on OS and tool of choice, but might look something like this:
14 |
15 | ```bash
16 | python3 -m venv venv
17 | source venv/bin/activate
18 | ```
19 |
20 | **Note**: `venv` is listed in the `.gitignore` file so it's the recommended virtual environment name
21 |
22 |
23 | ### Install project requirements
24 |
25 | ```bash
26 | pip3 install -r requirements.txt # eel's 'prod' requirements
27 | pip3 install -r requirements-test.txt # pytest and selenium
28 | pip3 install -r requirements-meta.txt # tox
29 | ```
30 |
31 | ### (Recommended) Run Automated Tests
32 | Tox is configured to run tests against each major version we support (3.7+). In order to run Tox as configured, you will need to install multiple versions of Python. See the pinned minor versions in `.python-version` for recommendations.
33 |
34 | #### Tox Setup
35 | Our Tox configuration requires [Chrome](https://www.google.com/chrome) and [ChromeDriver](https://chromedriver.chromium.org/home). See each of those respective project pages for more information on setting each up.
36 |
37 | **Note**: Pay attention to the version of Chrome that is installed on your OS because you need to select the compatible ChromeDriver version.
38 |
39 | #### Running Tests
40 |
41 | To test Eel against a specific version of Python you have installed, e.g. Python 3.7 in this case, run:
42 |
43 | ```bash
44 | tox -e py36
45 | ```
46 |
47 | To test Eel against all supported versions, run the following:
48 |
49 | ```bash
50 | tox
51 | ```
52 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Eel
2 |
3 | [](https://pypi.org/project/Eel/)
4 | [](https://pypistats.org/packages/eel)
5 | 
6 | [](https://pypi.org/project/Eel/)
7 |
8 | Eel is a little Python library for making simple Electron-like offline HTML/JS GUI apps, with full access to Python capabilities and libraries.
9 |
10 | > **Eel hosts a local webserver, then lets you annotate functions in Python so that they can be called from Javascript, and vice versa.**
11 |
12 | Eel is designed to take the hassle out of writing short and simple GUI applications. If you are familiar with Python and web development, probably just jump to [this example](https://github.com/ChrisKnott/Eel/tree/master/examples/04%20-%20file_access) which picks random file names out of the given folder (something that is impossible from a browser).
13 |
14 |
15 |
16 |
17 |
18 | - [Eel](#eel)
19 | - [Intro](#intro)
20 | - [Install](#install)
21 | - [Usage](#usage)
22 | - [Directory Structure](#directory-structure)
23 | - [Starting the app](#starting-the-app)
24 | - [App options](#app-options)
25 | - [Chrome/Chromium flags](#chromechromium-flags)
26 | - [Exposing functions](#exposing-functions)
27 | - [Eello, World!](#eello-world)
28 | - [Return values](#return-values)
29 | - [Callbacks](#callbacks)
30 | - [Synchronous returns](#synchronous-returns)
31 | - [Asynchronous Python](#asynchronous-python)
32 | - [Building distributable binary with PyInstaller](#building-distributable-binary-with-pyinstaller)
33 | - [Microsoft Edge](#microsoft-edge)
34 |
35 |
36 |
37 | ## Intro
38 |
39 | There are several options for making GUI apps in Python, but if you want to use HTML/JS (in order to use jQueryUI or Bootstrap, for example) then you generally have to write a lot of boilerplate code to communicate from the Client (Javascript) side to the Server (Python) side.
40 |
41 | The closest Python equivalent to Electron (to my knowledge) is [cefpython](https://github.com/cztomczak/cefpython). It is a bit heavy weight for what I wanted.
42 |
43 | Eel is not as fully-fledged as Electron or cefpython - it is probably not suitable for making full blown applications like Atom - but it is very suitable for making the GUI equivalent of little utility scripts that you use internally in your team.
44 |
45 | For some reason many of the best-in-class number crunching and maths libraries are in Python (Tensorflow, Numpy, Scipy etc) but many of the best visualization libraries are in Javascript (D3, THREE.js etc). Hopefully Eel makes it easy to combine these into simple utility apps for assisting your development.
46 |
47 | Join Eel's users and maintainers on [Discord](https://discord.com/invite/3nqXPFX), if you like.
48 |
49 | ## Install
50 |
51 | Install from pypi with `pip`:
52 |
53 | ```shell
54 | pip install eel
55 | ```
56 |
57 | To include support for HTML templating, currently using [Jinja2](https://pypi.org/project/Jinja2/#description):
58 |
59 | ```shell
60 | pip install eel[jinja2]
61 | ```
62 |
63 | ## Usage
64 |
65 | ### Directory Structure
66 |
67 | An Eel application will be split into a frontend consisting of various web-technology files (.html, .js, .css) and a backend consisting of various Python scripts.
68 |
69 | All the frontend files should be put in a single directory (they can be further divided into folders inside this if necessary).
70 |
71 | ```
72 | my_python_script.py <-- Python scripts
73 | other_python_module.py
74 | static_web_folder/ <-- Web folder
75 | main_page.html
76 | css/
77 | style.css
78 | img/
79 | logo.png
80 | ```
81 |
82 | ### Starting the app
83 |
84 | Suppose you put all the frontend files in a directory called `web`, including your start page `main.html`, then the app is started like this;
85 |
86 | ```python
87 | import eel
88 | eel.init('web')
89 | eel.start('main.html')
90 | ```
91 |
92 | This will start a webserver on the default settings (http://localhost:8000) and open a browser to http://localhost:8000/main.html.
93 |
94 | If Chrome or Chromium is installed then by default it will open in that in App Mode (with the `--app` cmdline flag), regardless of what the OS's default browser is set to (it is possible to override this behaviour).
95 |
96 | ### App options
97 |
98 | Additional options can be passed to `eel.start()` as keyword arguments.
99 |
100 | Some of the options include the mode the app is in (e.g. 'chrome'), the port the app runs on, the host name of the app, and adding additional command line flags.
101 |
102 | As of Eel v0.12.0, the following options are available to `start()`:
103 | - **mode**, a string specifying what browser to use (e.g. `'chrome'`, `'electron'`, `'edge'`,`'msie'`, `'custom'`). Can also be `None` or `False` to not open a window. *Default: `'chrome'`*
104 | - **host**, a string specifying what hostname to use for the Bottle server. *Default: `'localhost'`)*
105 | - **port**, an int specifying what port to use for the Bottle server. Use `0` for port to be picked automatically. *Default: `8000`*.
106 | - **block**, a bool saying whether or not the call to `start()` should block the calling thread. *Default: `True`*
107 | - **jinja_templates**, a string specifying a folder to use for Jinja2 templates, e.g. `my_templates`. *Default: `None`*
108 | - **cmdline_args**, a list of strings to pass to the command to start the browser. For example, we might add extra flags for Chrome; ```eel.start('main.html', mode='chrome-app', port=8080, cmdline_args=['--start-fullscreen', '--browser-startup-dialog'])```. *Default: `[]`*
109 | - **size**, a tuple of ints specifying the (width, height) of the main window in pixels *Default: `None`*
110 | - **position**, a tuple of ints specifying the (left, top) of the main window in pixels *Default: `None`*
111 | - **geometry**, a dictionary specifying the size and position for all windows. The keys should be the relative path of the page, and the values should be a dictionary of the form `{'size': (200, 100), 'position': (300, 50)}`. *Default: {}*
112 | - **close_callback**, a lambda or function that is called when a websocket to a window closes (i.e. when the user closes the window). It should take two arguments; a string which is the relative path of the page that just closed, and a list of other websockets that are still open. *Default: `None`*
113 | - **app**, an instance of Bottle which will be used rather than creating a fresh one. This can be used to install middleware on the instance before starting eel, e.g. for session management, authentication, etc. If your `app` is not a Bottle instance, you will need to call `eel.register_eel_routes(app)` on your custom app instance.
114 | - **shutdown_delay**, timer configurable for Eel's shutdown detection mechanism, whereby when any websocket closes, it waits `shutdown_delay` seconds, and then checks if there are now any websocket connections. If not, then Eel closes. In case the user has closed the browser and wants to exit the program. By default, the value of **shutdown_delay** is `1.0` second
115 |
116 |
117 |
118 | ### Exposing functions
119 |
120 | In addition to the files in the frontend folder, a Javascript library will be served at `/eel.js`. You should include this in any pages:
121 |
122 | ```html
123 |
124 | ```
125 |
126 | Including this library creates an `eel` object which can be used to communicate with the Python side.
127 |
128 | Any functions in the Python code which are decorated with `@eel.expose` like this...
129 |
130 | ```python
131 | @eel.expose
132 | def my_python_function(a, b):
133 | print(a, b, a + b)
134 | ```
135 |
136 | ...will appear as methods on the `eel` object on the Javascript side, like this...
137 |
138 | ```javascript
139 | console.log("Calling Python...");
140 | eel.my_python_function(1, 2); // This calls the Python function that was decorated
141 | ```
142 |
143 | Similarly, any Javascript functions which are exposed like this...
144 |
145 | ```javascript
146 | eel.expose(my_javascript_function);
147 | function my_javascript_function(a, b, c, d) {
148 | if (a < b) {
149 | console.log(c * d);
150 | }
151 | }
152 | ```
153 |
154 | can be called from the Python side like this...
155 |
156 | ```python
157 | print('Calling Javascript...')
158 | eel.my_javascript_function(1, 2, 3, 4) # This calls the Javascript function
159 | ```
160 |
161 | The exposed name can also be overridden by passing in a second argument. If your app minifies JavaScript during builds, this may be necessary to ensure that functions can be resolved on the Python side:
162 |
163 | ```javascript
164 | eel.expose(someFunction, "my_javascript_function");
165 | ```
166 |
167 | When passing complex objects as arguments, bear in mind that internally they are converted to JSON and sent down a websocket (a process that potentially loses information).
168 |
169 | ### Eello, World!
170 |
171 | > See full example in: [examples/01 - hello_world](https://github.com/ChrisKnott/Eel/tree/master/examples/01%20-%20hello_world)
172 |
173 | Putting this together into a **Hello, World!** example, we have a short HTML page, `web/hello.html`:
174 |
175 | ```html
176 |
177 |
178 |
179 | Hello, World!
180 |
181 |
182 |
183 |
192 |
193 |
194 |
195 | Hello, World!
196 |
197 |
198 | ```
199 |
200 | and a short Python script `hello.py`:
201 |
202 | ```python
203 | import eel
204 |
205 | # Set web files folder and optionally specify which file types to check for eel.expose()
206 | # *Default allowed_extensions are: ['.js', '.html', '.txt', '.htm', '.xhtml']
207 | eel.init('web', allowed_extensions=['.js', '.html'])
208 |
209 | @eel.expose # Expose this function to Javascript
210 | def say_hello_py(x):
211 | print('Hello from %s' % x)
212 |
213 | say_hello_py('Python World!')
214 | eel.say_hello_js('Python World!') # Call a Javascript function
215 |
216 | eel.start('hello.html') # Start (this blocks and enters loop)
217 | ```
218 |
219 | If we run the Python script (`python hello.py`), then a browser window will open displaying `hello.html`, and we will see...
220 |
221 | ```
222 | Hello from Python World!
223 | Hello from Javascript World!
224 | ```
225 |
226 | ...in the terminal, and...
227 |
228 | ```
229 | Hello from Javascript World!
230 | Hello from Python World!
231 | ```
232 |
233 | ...in the browser console (press F12 to open).
234 |
235 | You will notice that in the Python code, the Javascript function is called before the browser window is even started - any early calls like this are queued up and then sent once the websocket has been established.
236 |
237 | ### Return values
238 |
239 | While we want to think of our code as comprising a single application, the Python interpreter and the browser window run in separate processes. This can make communicating back and forth between them a bit of a mess, especially if we always had to explicitly _send_ values from one side to the other.
240 |
241 | Eel supports two ways of retrieving _return values_ from the other side of the app, which helps keep the code concise.
242 |
243 | To prevent hanging forever on the Python side, a timeout has been put in place for trying to retrieve values from
244 | the JavaScript side, which defaults to 10000 milliseconds (10 seconds). This can be changed with the `_js_result_timeout` parameter to `eel.init`. There is no corresponding timeout on the JavaScript side.
245 |
246 | #### Callbacks
247 |
248 | When you call an exposed function, you can immediately pass a callback function afterwards. This callback will automatically be called asynchronously with the return value when the function has finished executing on the other side.
249 |
250 | For example, if we have the following function defined and exposed in Javascript:
251 |
252 | ```javascript
253 | eel.expose(js_random);
254 | function js_random() {
255 | return Math.random();
256 | }
257 | ```
258 |
259 | Then in Python we can retrieve random values from the Javascript side like so:
260 |
261 | ```python
262 | def print_num(n):
263 | print('Got this from Javascript:', n)
264 |
265 | # Call Javascript function, and pass explicit callback function
266 | eel.js_random()(print_num)
267 |
268 | # Do the same with an inline lambda as callback
269 | eel.js_random()(lambda n: print('Got this from Javascript:', n))
270 | ```
271 |
272 | (It works exactly the same the other way around).
273 |
274 | #### Synchronous returns
275 |
276 | In most situations, the calls to the other side are to quickly retrieve some piece of data, such as the state of a widget or contents of an input field. In these cases it is more convenient to just synchronously wait a few milliseconds then continue with your code, rather than breaking the whole thing up into callbacks.
277 |
278 | To synchronously retrieve the return value, simply pass nothing to the second set of brackets. So in Python we would write:
279 |
280 | ```python
281 | n = eel.js_random()() # This immediately returns the value
282 | print('Got this from Javascript:', n)
283 | ```
284 |
285 | You can only perform synchronous returns after the browser window has started (after calling `eel.start()`), otherwise obviously the call will hang.
286 |
287 | In Javascript, the language doesn't allow us to block while we wait for a callback, except by using `await` from inside an `async` function. So the equivalent code from the Javascript side would be:
288 |
289 | ```javascript
290 | async function run() {
291 | // Inside a function marked 'async' we can use the 'await' keyword.
292 |
293 | let n = await eel.py_random()(); // Must prefix call with 'await', otherwise it's the same syntax
294 | console.log("Got this from Python: " + n);
295 | }
296 |
297 | run();
298 | ```
299 |
300 | ## Asynchronous Python
301 |
302 | Eel is built on Bottle and Gevent, which provide an asynchronous event loop similar to Javascript. A lot of Python's standard library implicitly assumes there is a single execution thread - to deal with this, Gevent can "[monkey patch](https://en.wikipedia.org/wiki/Monkey_patch)" many of the standard modules such as `time`. ~~This monkey patching is done automatically when you call `import eel`~~. If you need monkey patching you should `import gevent.monkey` and call `gevent.monkey.patch_all()` _before_ you `import eel`. Monkey patching can interfere with things like debuggers so should be avoided unless necessary.
303 |
304 | For most cases you should be fine by avoiding using `time.sleep()` and instead using the versions provided by `gevent`. For convenience, the two most commonly needed gevent methods, `sleep()` and `spawn()` are provided directly from Eel (to save importing `time` and/or `gevent` as well).
305 |
306 | In this example...
307 |
308 | ```python
309 | import eel
310 | eel.init('web')
311 |
312 | def my_other_thread():
313 | while True:
314 | print("I'm a thread")
315 | eel.sleep(1.0) # Use eel.sleep(), not time.sleep()
316 |
317 | eel.spawn(my_other_thread)
318 |
319 | eel.start('main.html', block=False) # Don't block on this call
320 |
321 | while True:
322 | print("I'm a main loop")
323 | eel.sleep(1.0) # Use eel.sleep(), not time.sleep()
324 | ```
325 |
326 | ...we would then have three "threads" (greenlets) running;
327 |
328 | 1. Eel's internal thread for serving the web folder
329 | 2. The `my_other_thread` method, repeatedly printing **"I'm a thread"**
330 | 3. The main Python thread, which would be stuck in the final `while` loop, repeatedly printing **"I'm a main loop"**
331 |
332 | ## Building distributable binary with PyInstaller
333 |
334 | If you want to package your app into a program that can be run on a computer without a Python interpreter installed, you should use **PyInstaller**.
335 |
336 | 1. Configure a virtualenv with desired Python version and minimum necessary Python packages
337 | 2. Install PyInstaller `pip install PyInstaller`
338 | 3. In your app's folder, run `python -m eel [your_main_script] [your_web_folder]` (for example, you might run `python -m eel hello.py web`)
339 | 4. This will create a new folder `dist/`
340 | 5. Valid PyInstaller flags can be passed through, such as excluding modules with the flag: `--exclude module_name`. For example, you might run `python -m eel file_access.py web --exclude win32com --exclude numpy --exclude cryptography`
341 | 6. When happy that your app is working correctly, add `--onefile --noconsole` flags to build a single executable file
342 |
343 | Consult the [documentation for PyInstaller](http://PyInstaller.readthedocs.io/en/stable/) for more options.
344 |
345 | ## Microsoft Edge
346 |
347 | For Windows 10 users, Microsoft Edge (`eel.start(.., mode='edge')`) is installed by default and a useful fallback if a preferred browser is not installed. See the examples:
348 |
349 | - A Hello World example using Microsoft Edge: [examples/01 - hello_world-Edge/](https://github.com/ChrisKnott/Eel/tree/master/examples/01%20-%20hello_world-Edge)
350 | - Example implementing browser-fallbacks: [examples/07 - CreateReactApp/eel_CRA.py](https://github.com/ChrisKnott/Eel/tree/master/examples/07%20-%20CreateReactApp/eel_CRA.py)
351 |
--------------------------------------------------------------------------------
/eel/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | from builtins import range
3 | import traceback
4 | from io import open
5 | from typing import Union, Any, Dict, List, Set, Tuple, Optional, Callable
6 | from typing_extensions import Literal
7 | from eel.types import OptionsDictT, WebSocketT
8 | import gevent as gvt
9 | import json as jsn
10 | import bottle as btl
11 | try:
12 | import bottle_websocket as wbs
13 | except ImportError:
14 | import bottle.ext.websocket as wbs
15 | import re as rgx
16 | import os
17 | import eel.browsers as brw
18 | import pyparsing as pp
19 | import random as rnd
20 | import sys
21 | import pkg_resources as pkg
22 | import socket
23 | import mimetypes
24 |
25 |
26 | mimetypes.add_type('application/javascript', '.js')
27 | _eel_js_file: str = pkg.resource_filename('eel', 'eel.js')
28 | _eel_js: str = open(_eel_js_file, encoding='utf-8').read()
29 | _websockets: List[Tuple[Any, WebSocketT]] = []
30 | _call_return_values: Dict[Any, Any] = {}
31 | _call_return_callbacks: Dict[float, Tuple[Callable[..., Any], Optional[Callable[..., Any]]]] = {}
32 | _call_number: int = 0
33 | _exposed_functions: Dict[Any, Any] = {}
34 | _js_functions: List[Any] = []
35 | _mock_queue: List[Any] = []
36 | _mock_queue_done: Set[Any] = set()
37 | _shutdown: Optional[gvt.Greenlet] = None # Later assigned as global by _websocket_close()
38 | root_path: str # Later assigned as global by init()
39 |
40 | # The maximum time (in milliseconds) that Python will try to retrieve a return value for functions executing in JS
41 | # Can be overridden through `eel.init` with the kwarg `js_result_timeout` (default: 10000)
42 | _js_result_timeout: int = 10000
43 |
44 | # Attribute holding the start args from calls to eel.start()
45 | _start_args: OptionsDictT = {}
46 |
47 | # == Temporary (suppressible) error message to inform users of breaking API change for v1.0.0 ===
48 | api_error_message: str = '''
49 | ----------------------------------------------------------------------------------
50 | 'options' argument deprecated in v1.0.0, see https://github.com/ChrisKnott/Eel
51 | To suppress this error, add 'suppress_error=True' to start() call.
52 | This option will be removed in future versions
53 | ----------------------------------------------------------------------------------
54 | '''
55 | # ===============================================================================================
56 |
57 |
58 | # Public functions
59 |
60 |
61 | def expose(name_or_function: Optional[Callable[..., Any]] = None) -> Callable[..., Any]:
62 | '''Decorator to expose Python callables via Eel's JavaScript API.
63 |
64 | When an exposed function is called, a callback function can be passed
65 | immediately afterwards. This callback will be called asynchronously with
66 | the return value (possibly `None`) when the Python function has finished
67 | executing.
68 |
69 | Blocking calls to the exposed function from the JavaScript side are only
70 | possible using the :code:`await` keyword inside an :code:`async function`.
71 | These still have to make a call to the response, i.e.
72 | :code:`await eel.py_random()();` inside an :code:`async function` will work,
73 | but just :code:`await eel.py_random();` will not.
74 |
75 | :Example:
76 |
77 | In Python do:
78 |
79 | .. code-block:: python
80 |
81 | @expose
82 | def say_hello_py(name: str = 'You') -> None:
83 | print(f'{name} said hello from the JavaScript world!')
84 |
85 | In JavaScript do:
86 |
87 | .. code-block:: javascript
88 |
89 | eel.say_hello_py('Alice')();
90 |
91 | Expected output on the Python console::
92 |
93 | Alice said hello from the JavaScript world!
94 |
95 | '''
96 | # Deal with '@eel.expose()' - treat as '@eel.expose'
97 | if name_or_function is None:
98 | return expose
99 |
100 | if isinstance(name_or_function, str): # Called as '@eel.expose("my_name")'
101 | name = name_or_function
102 |
103 | def decorator(function: Callable[..., Any]) -> Any:
104 | _expose(name, function)
105 | return function
106 | return decorator
107 | else:
108 | function = name_or_function
109 | _expose(function.__name__, function)
110 | return function
111 |
112 |
113 | # PyParsing grammar for parsing exposed functions in JavaScript code
114 | # Examples: `eel.expose(w, "func_name")`, `eel.expose(func_name)`, `eel.expose((function (e){}), "func_name")`
115 | EXPOSED_JS_FUNCTIONS: pp.ZeroOrMore = pp.ZeroOrMore(
116 | pp.Suppress(
117 | pp.SkipTo(pp.Literal('eel.expose('))
118 | + pp.Literal('eel.expose(')
119 | + pp.Optional(
120 | pp.Or([pp.nestedExpr(), pp.Word(pp.printables, excludeChars=',')]) + pp.Literal(',')
121 | )
122 | )
123 | + pp.Suppress(pp.Regex(r'["\']?'))
124 | + pp.Word(pp.printables, excludeChars='"\')')
125 | + pp.Suppress(pp.Regex(r'["\']?\s*\)')),
126 | )
127 |
128 |
129 | def init(
130 | path: str,
131 | allowed_extensions: List[str] = ['.js', '.html', '.txt', '.htm', '.xhtml', '.vue'],
132 | js_result_timeout: int = 10000) -> None:
133 | '''Initialise Eel.
134 |
135 | This function should be called before :func:`start()` to initialise the
136 | parameters for the web interface, such as the path to the files to be
137 | served.
138 |
139 | :param path: Sets the path on the filesystem where files to be served to
140 | the browser are located, e.g. :file:`web`.
141 | :param allowed_extensions: A list of filename extensions which will be
142 | parsed for exposed eel functions which should be callable from python.
143 | Files with extensions not in *allowed_extensions* will still be served,
144 | but any JavaScript functions, even if marked as exposed, will not be
145 | accessible from python.
146 | *Default:* :code:`['.js', '.html', '.txt', '.htm', '.xhtml', '.vue']`.
147 | :param js_result_timeout: How long Eel should be waiting to register the
148 | results from a call to Eel's JavaScript API before before timing out.
149 | *Default:* :code:`10000` milliseconds.
150 | '''
151 | global root_path, _js_functions, _js_result_timeout
152 | root_path = _get_real_path(path)
153 |
154 | js_functions = set()
155 | for root, _, files in os.walk(root_path):
156 | for name in files:
157 | if not any(name.endswith(ext) for ext in allowed_extensions):
158 | continue
159 |
160 | try:
161 | with open(os.path.join(root, name), encoding='utf-8') as file:
162 | contents = file.read()
163 | expose_calls = set()
164 | matches = EXPOSED_JS_FUNCTIONS.parseString(contents).asList()
165 | for expose_call in matches:
166 | # Verify that function name is valid
167 | msg = "eel.expose() call contains '(' or '='"
168 | assert rgx.findall(r'[\(=]', expose_call) == [], msg
169 | expose_calls.add(expose_call)
170 | js_functions.update(expose_calls)
171 | except UnicodeDecodeError:
172 | pass # Malformed file probably
173 |
174 | _js_functions = list(js_functions)
175 | for js_function in _js_functions:
176 | _mock_js_function(js_function)
177 |
178 | _js_result_timeout = js_result_timeout
179 |
180 |
181 | def start(
182 | *start_urls: str,
183 | mode: Optional[Union[str, Literal[False]]] = 'chrome',
184 | host: str = 'localhost',
185 | port: int = 8000,
186 | block: bool = True,
187 | jinja_templates: Optional[str] = None,
188 | cmdline_args: List[str] = ['--disable-http-cache'],
189 | size: Optional[Tuple[int, int]] = None,
190 | position: Optional[Tuple[int, int]] = None,
191 | geometry: Dict[str, Tuple[int, int]] = {},
192 | close_callback: Optional[Callable[..., Any]] = None,
193 | app_mode: bool = True,
194 | all_interfaces: bool = False,
195 | disable_cache: bool = True,
196 | default_path: str = 'index.html',
197 | app: btl.Bottle = btl.default_app(),
198 | shutdown_delay: float = 1.0,
199 | suppress_error: bool = False) -> None:
200 | '''Start the Eel app.
201 |
202 | Suppose you put all the frontend files in a directory called
203 | :file:`web`, including your start page :file:`main.html`, then the app
204 | is started like this:
205 |
206 | .. code-block:: python
207 |
208 | import eel
209 | eel.init('web')
210 | eel.start('main.html')
211 |
212 | This will start a webserver on the default settings
213 | (http://localhost:8000) and open a browser to
214 | http://localhost:8000/main.html.
215 |
216 | If Chrome or Chromium is installed then by default it will open that in
217 | *App Mode* (with the `--app` cmdline flag), regardless of what the OS's
218 | default browser is set to (it is possible to override this behaviour).
219 |
220 | :param mode: What browser is used, e.g. :code:`'chrome'`,
221 | :code:`'electron'`, :code:`'edge'`, :code:`'custom'`. Can also be
222 | `None` or `False` to not open a window. *Default:* :code:`'chrome'`.
223 | :param host: Hostname used for Bottle server. *Default:*
224 | :code:`'localhost'`.
225 | :param port: Port used for Bottle server. Use :code:`0` for port to be
226 | picked automatically. *Default:* :code:`8000`.
227 | :param block: Whether the call to :func:`start()` blocks the calling
228 | thread. *Default:* `True`.
229 | :param jinja_templates: Folder for :mod:`jinja2` templates, e.g.
230 | :file:`my_templates`. *Default:* `None`.
231 | :param cmdline_args: A list of strings to pass to the command starting the
232 | browser. For example, we might add extra flags to Chrome with
233 | :code:`eel.start('main.html', mode='chrome-app', port=8080,
234 | cmdline_args=['--start-fullscreen', '--browser-startup-dialog'])`.
235 | *Default:* :code:`[]`.
236 | :param size: Tuple specifying the (width, height) of the main window in
237 | pixels. *Default:* `None`.
238 | :param position: Tuple specifying the (left, top) position of the main
239 | window in pixels. *Default*: `None`.
240 | :param geometry: A dictionary of specifying the size/position for all
241 | windows. The keys should be the relative path of the page, and the
242 | values should be a dictionary of the form
243 | :code:`{'size': (200, 100), 'position': (300, 50)}`. *Default:*
244 | :code:`{}`.
245 | :param close_callback: A lambda or function that is called when a websocket
246 | or window closes (i.e. when the user closes the window). It should take
247 | two arguments: a string which is the relative path of the page that
248 | just closed, and a list of the other websockets that are still open.
249 | *Default:* `None`.
250 | :param app_mode: Whether to run Chrome/Edge in App Mode. You can also
251 | specify *mode* as :code:`mode='chrome-app'` as a shorthand to start
252 | Chrome in App Mode.
253 | :param all_interfaces: Whether to allow the :mod:`bottle` server to listen
254 | for connections on all interfaces.
255 | :param disable_cache: Sets the no-store response header when serving
256 | assets.
257 | :param default_path: The default file to retrieve for the root URL.
258 | :param app: An instance of :class:`bottle.Bottle` which will be used rather
259 | than creating a fresh one. This can be used to install middleware on
260 | the instance before starting Eel, e.g. for session management,
261 | authentication, etc. If *app* is not a :class:`bottle.Bottle` instance,
262 | you will need to call :code:`eel.register_eel_routes(app)` on your
263 | custom app instance.
264 | :param shutdown_delay: Timer configurable for Eel's shutdown detection
265 | mechanism, whereby when any websocket closes, it waits *shutdown_delay*
266 | seconds, and then checks if there are now any websocket connections.
267 | If not, then Eel closes. In case the user has closed the browser and
268 | wants to exit the program. *Default:* :code:`1.0` seconds.
269 | :param suppress_error: Temporary (suppressible) error message to inform
270 | users of breaking API change for v1.0.0. Set to `True` to suppress
271 | the error message.
272 | '''
273 | _start_args.update({
274 | 'mode': mode,
275 | 'host': host,
276 | 'port': port,
277 | 'block': block,
278 | 'jinja_templates': jinja_templates,
279 | 'cmdline_args': cmdline_args,
280 | 'size': size,
281 | 'position': position,
282 | 'geometry': geometry,
283 | 'close_callback': close_callback,
284 | 'app_mode': app_mode,
285 | 'all_interfaces': all_interfaces,
286 | 'disable_cache': disable_cache,
287 | 'default_path': default_path,
288 | 'app': app,
289 | 'shutdown_delay': shutdown_delay,
290 | 'suppress_error': suppress_error,
291 | })
292 |
293 | if _start_args['port'] == 0:
294 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
295 | sock.bind(('localhost', 0))
296 | _start_args['port'] = sock.getsockname()[1]
297 | sock.close()
298 |
299 | if _start_args['jinja_templates'] is not None:
300 | from jinja2 import Environment, FileSystemLoader, select_autoescape
301 | if not isinstance(_start_args['jinja_templates'], str):
302 | raise TypeError("'jinja_templates' start_arg/option must be of type str")
303 | templates_path = os.path.join(root_path, _start_args['jinja_templates'])
304 | _start_args['jinja_env'] = Environment(
305 | loader=FileSystemLoader(templates_path),
306 | autoescape=select_autoescape(['html', 'xml'])
307 | )
308 |
309 | # verify shutdown_delay is correct value
310 | if not isinstance(_start_args['shutdown_delay'], (int, float)):
311 | raise ValueError(
312 | '`shutdown_delay` must be a number, '
313 | 'got a {}'.format(type(_start_args['shutdown_delay']))
314 | )
315 |
316 | # Launch the browser to the starting URLs
317 | show(*start_urls)
318 |
319 | def run_lambda() -> None:
320 | if _start_args['all_interfaces'] is True:
321 | HOST = '0.0.0.0'
322 | else:
323 | if not isinstance(_start_args['host'], str):
324 | raise TypeError("'host' start_arg/option must be of type str")
325 | HOST = _start_args['host']
326 |
327 | app = _start_args['app']
328 |
329 | if isinstance(app, btl.Bottle):
330 | register_eel_routes(app)
331 | else:
332 | register_eel_routes(btl.default_app())
333 |
334 | btl.run(
335 | host=HOST,
336 | port=_start_args['port'],
337 | server=wbs.GeventWebSocketServer,
338 | quiet=True,
339 | app=app) # Always returns None
340 |
341 | # Start the webserver
342 | if _start_args['block']:
343 | run_lambda()
344 | else:
345 | spawn(run_lambda)
346 |
347 |
348 | def show(*start_urls: str) -> None:
349 | '''Show the specified URL(s) in the browser.
350 |
351 | Suppose you have two files in your :file:`web` folder. The file
352 | :file:`hello.html` regularly includes :file:`eel.js` and provides
353 | interactivity, and the file :file:`goodbye.html` does not include
354 | :file:`eel.js` and simply provides plain HTML content not reliant on Eel.
355 |
356 | First, we defien a callback function to be called when the browser
357 | window is closed:
358 |
359 | .. code-block:: python
360 |
361 | def last_calls():
362 | eel.show('goodbye.html')
363 |
364 | Now we initialise and start Eel, with a :code:`close_callback` to our
365 | function:
366 |
367 | ..code-block:: python
368 |
369 | eel.init('web')
370 | eel.start('hello.html', mode='chrome-app', close_callback=last_calls)
371 |
372 | When the websocket from :file:`hello.html` is closed (e.g. because the
373 | user closed the browser window), Eel will wait *shutdown_delay* seconds
374 | (by default 1 second), then call our :code:`last_calls()` function, which
375 | opens another window with the :file:`goodbye.html` shown before our Eel app
376 | terminates.
377 |
378 | :param start_urls: One or more URLs to be opened.
379 | '''
380 | brw.open(list(start_urls), _start_args)
381 |
382 |
383 | def sleep(seconds: Union[int, float]) -> None:
384 | '''A non-blocking sleep call compatible with the Gevent event loop.
385 |
386 | .. note::
387 | While this function simply wraps :func:`gevent.sleep()`, it is better
388 | to call :func:`eel.sleep()` in your eel app, as this will ensure future
389 | compatibility in case the implementation of Eel should change in some
390 | respect.
391 |
392 | :param seconds: The number of seconds to sleep.
393 | '''
394 | gvt.sleep(seconds)
395 |
396 |
397 | def spawn(function: Callable[..., Any], *args: Any, **kwargs: Any) -> gvt.Greenlet:
398 | '''Spawn a new Greenlet.
399 |
400 | Calling this function will spawn a new :class:`gevent.Greenlet` running
401 | *function* asynchronously.
402 |
403 | .. caution::
404 | If you spawn your own Greenlets to run in addition to those spawned by
405 | Eel's internal core functionality, you will have to ensure that those
406 | Greenlets will terminate as appropriate (either by returning or by
407 | being killed via Gevent's kill mechanism), otherwise your app may not
408 | terminate correctly when Eel itself terminates.
409 |
410 | :param function: The function to be called and run as the Greenlet.
411 | :param *args: Any positional arguments that should be passed to *function*.
412 | :param **kwargs: Any key-word arguments that should be passed to
413 | *function*.
414 | '''
415 | return gvt.spawn(function, *args, **kwargs)
416 |
417 |
418 | # Bottle Routes
419 |
420 |
421 | def _eel() -> str:
422 | start_geometry = {'default': {'size': _start_args['size'],
423 | 'position': _start_args['position']},
424 | 'pages': _start_args['geometry']}
425 |
426 | page = _eel_js.replace('/** _py_functions **/',
427 | '_py_functions: %s,' % list(_exposed_functions.keys()))
428 | page = page.replace('/** _start_geometry **/',
429 | '_start_geometry: %s,' % _safe_json(start_geometry))
430 | btl.response.content_type = 'application/javascript'
431 | _set_response_headers(btl.response)
432 | return page
433 |
434 |
435 | def _root() -> btl.Response:
436 | if not isinstance(_start_args['default_path'], str):
437 | raise TypeError("'default_path' start_arg/option must be of type str")
438 | return _static(_start_args['default_path'])
439 |
440 |
441 | def _static(path: str) -> btl.Response:
442 | response = None
443 | if 'jinja_env' in _start_args and 'jinja_templates' in _start_args:
444 | if not isinstance(_start_args['jinja_templates'], str):
445 | raise TypeError("'jinja_templates' start_arg/option must be of type str")
446 | template_prefix = _start_args['jinja_templates'] + '/'
447 | if path.startswith(template_prefix):
448 | n = len(template_prefix)
449 | template = _start_args['jinja_env'].get_template(path[n:])
450 | response = btl.HTTPResponse(template.render())
451 |
452 | if response is None:
453 | response = btl.static_file(path, root=root_path)
454 |
455 | _set_response_headers(response)
456 | return response
457 |
458 |
459 | def _websocket(ws: WebSocketT) -> None:
460 | global _websockets
461 |
462 | for js_function in _js_functions:
463 | _import_js_function(js_function)
464 |
465 | page = btl.request.query.page
466 | if page not in _mock_queue_done:
467 | for call in _mock_queue:
468 | _repeated_send(ws, _safe_json(call))
469 | _mock_queue_done.add(page)
470 |
471 | _websockets += [(page, ws)]
472 |
473 | while True:
474 | msg = ws.receive()
475 | if msg is not None:
476 | message = jsn.loads(msg)
477 | spawn(_process_message, message, ws)
478 | else:
479 | _websockets.remove((page, ws))
480 | break
481 |
482 | _websocket_close(page)
483 |
484 |
485 | BOTTLE_ROUTES: Dict[str, Tuple[Callable[..., Any], Dict[Any, Any]]] = {
486 | "/eel.js": (_eel, dict()),
487 | "/": (_root, dict()),
488 | "/": (_static, dict()),
489 | "/eel": (_websocket, dict(apply=[wbs.websocket]))
490 | }
491 |
492 |
493 | def register_eel_routes(app: btl.Bottle) -> None:
494 | '''Register the required eel routes with `app`.
495 |
496 | .. note::
497 |
498 | :func:`eel.register_eel_routes()` is normally invoked implicitly by
499 | :func:`eel.start()` and does not need to be called explicitly in most
500 | cases. Registering the eel routes explicitly is only needed if you are
501 | passing something other than an instance of :class:`bottle.Bottle` to
502 | :func:`eel.start()`.
503 |
504 | :Example:
505 |
506 | >>> app = bottle.Bottle()
507 | >>> eel.register_eel_routes(app)
508 | >>> middleware = beaker.middleware.SessionMiddleware(app)
509 | >>> eel.start(app=middleware)
510 |
511 | '''
512 | for route_path, route_params in BOTTLE_ROUTES.items():
513 | route_func, route_kwargs = route_params
514 | app.route(path=route_path, callback=route_func, **route_kwargs)
515 |
516 |
517 | # Private functions
518 |
519 |
520 | def _safe_json(obj: Any) -> str:
521 | return jsn.dumps(obj, default=lambda o: None)
522 |
523 |
524 | def _repeated_send(ws: WebSocketT, msg: str) -> None:
525 | for attempt in range(100):
526 | try:
527 | ws.send(msg)
528 | break
529 | except Exception:
530 | sleep(0.001)
531 |
532 |
533 | def _process_message(message: Dict[str, Any], ws: WebSocketT) -> None:
534 | if 'call' in message:
535 | error_info = {}
536 | try:
537 | return_val = _exposed_functions[message['name']](*message['args'])
538 | status = 'ok'
539 | except Exception as e:
540 | err_traceback = traceback.format_exc()
541 | traceback.print_exc()
542 | return_val = None
543 | status = 'error'
544 | error_info['errorText'] = repr(e)
545 | error_info['errorTraceback'] = err_traceback
546 | _repeated_send(ws, _safe_json({ 'return': message['call'],
547 | 'status': status,
548 | 'value': return_val,
549 | 'error': error_info,}))
550 | elif 'return' in message:
551 | call_id = message['return']
552 | if call_id in _call_return_callbacks:
553 | callback, error_callback = _call_return_callbacks.pop(call_id)
554 | if message['status'] == 'ok':
555 | callback(message['value'])
556 | elif message['status'] == 'error' and error_callback is not None:
557 | error_callback(message['error'], message['stack'])
558 | else:
559 | _call_return_values[call_id] = message['value']
560 |
561 | else:
562 | print('Invalid message received: ', message)
563 |
564 |
565 | def _get_real_path(path: str) -> str:
566 | if getattr(sys, 'frozen', False):
567 | return os.path.join(sys._MEIPASS, path) # type: ignore # sys._MEIPASS is dynamically added by PyInstaller
568 | else:
569 | return os.path.abspath(path)
570 |
571 |
572 | def _mock_js_function(f: str) -> None:
573 | exec('%s = lambda *args: _mock_call("%s", args)' % (f, f), globals())
574 |
575 |
576 | def _import_js_function(f: str) -> None:
577 | exec('%s = lambda *args: _js_call("%s", args)' % (f, f), globals())
578 |
579 |
580 | def _call_object(name: str, args: Any) -> Dict[str, Any]:
581 | global _call_number
582 | _call_number += 1
583 | call_id = _call_number + rnd.random()
584 | return {'call': call_id, 'name': name, 'args': args}
585 |
586 |
587 | def _mock_call(name: str, args: Any) -> Callable[[Optional[Callable[..., Any]], Optional[Callable[..., Any]]], Any]:
588 | call_object = _call_object(name, args)
589 | global _mock_queue
590 | _mock_queue += [call_object]
591 | return _call_return(call_object)
592 |
593 |
594 | def _js_call(name: str, args: Any) -> Callable[[Optional[Callable[..., Any]], Optional[Callable[..., Any]]], Any]:
595 | call_object = _call_object(name, args)
596 | for _, ws in _websockets:
597 | _repeated_send(ws, _safe_json(call_object))
598 | return _call_return(call_object)
599 |
600 |
601 | def _call_return(call: Dict[str, Any]) -> Callable[[Optional[Callable[..., Any]], Optional[Callable[..., Any]]], Any]:
602 | global _js_result_timeout
603 | call_id = call['call']
604 |
605 | def return_func(callback: Optional[Callable[..., Any]] = None,
606 | error_callback: Optional[Callable[..., Any]] = None) -> Any:
607 | if callback is not None:
608 | _call_return_callbacks[call_id] = (callback, error_callback)
609 | else:
610 | for w in range(_js_result_timeout):
611 | if call_id in _call_return_values:
612 | return _call_return_values.pop(call_id)
613 | sleep(0.001)
614 | return return_func
615 |
616 |
617 | def _expose(name: str, function: Callable[..., Any]) -> None:
618 | msg = 'Already exposed function with name "%s"' % name
619 | assert name not in _exposed_functions, msg
620 | _exposed_functions[name] = function
621 |
622 |
623 | def _detect_shutdown() -> None:
624 | if len(_websockets) == 0:
625 | sys.exit()
626 |
627 |
628 | def _websocket_close(page: str) -> None:
629 | global _shutdown
630 |
631 | close_callback = _start_args.get('close_callback')
632 |
633 | if close_callback is not None:
634 | if not callable(close_callback):
635 | raise TypeError("'close_callback' start_arg/option must be callable or None")
636 | sockets = [p for _, p in _websockets]
637 | close_callback(page, sockets)
638 | else:
639 | if isinstance(_shutdown, gvt.Greenlet):
640 | _shutdown.kill()
641 |
642 | _shutdown = gvt.spawn_later(_start_args['shutdown_delay'], _detect_shutdown)
643 |
644 |
645 | def _set_response_headers(response: btl.Response) -> None:
646 | if _start_args['disable_cache']:
647 | # https://stackoverflow.com/a/24748094/280852
648 | response.set_header('Cache-Control', 'no-store')
649 |
--------------------------------------------------------------------------------
/eel/__main__.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import pkg_resources as pkg
3 | import PyInstaller.__main__ as pyi
4 | import os
5 | from argparse import ArgumentParser, Namespace
6 | from typing import List
7 |
8 | parser: ArgumentParser = ArgumentParser(description="""
9 | Eel is a little Python library for making simple Electron-like offline HTML/JS GUI apps,
10 | with full access to Python capabilities and libraries.
11 | """)
12 | parser.add_argument(
13 | "main_script",
14 | type=str,
15 | help="Main python file to run app from"
16 | )
17 | parser.add_argument(
18 | "web_folder",
19 | type=str,
20 | help="Folder including all web files including file as html, css, ico, etc."
21 | )
22 | args: Namespace
23 | unknown_args: List[str]
24 | args, unknown_args = parser.parse_known_args()
25 | main_script: str = args.main_script
26 | web_folder: str = args.web_folder
27 |
28 | print("Building executable with main script '%s' and web folder '%s'...\n" %
29 | (main_script, web_folder))
30 |
31 | eel_js_file: str = pkg.resource_filename('eel', 'eel.js')
32 | js_file_arg: str = '%s%seel' % (eel_js_file, os.pathsep)
33 | web_folder_arg: str = '%s%s%s' % (web_folder, os.pathsep, web_folder)
34 |
35 | needed_args: List[str] = ['--hidden-import', 'bottle_websocket',
36 | '--add-data', js_file_arg, '--add-data', web_folder_arg]
37 | full_args: List[str] = [main_script] + needed_args + unknown_args
38 | print('Running:\npyinstaller', ' '.join(full_args), '\n')
39 |
40 | pyi.run(full_args)
41 |
--------------------------------------------------------------------------------
/eel/browsers.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import subprocess as sps
3 | import webbrowser as wbr
4 | from typing import Union, List, Dict, Iterable, Optional
5 | from types import ModuleType
6 |
7 | from eel.types import OptionsDictT
8 | import eel.chrome as chm
9 | import eel.electron as ele
10 | import eel.edge as edge
11 | import eel.msIE as ie
12 | #import eel.firefox as ffx TODO
13 | #import eel.safari as saf TODO
14 |
15 | _browser_paths: Dict[str, str] = {}
16 | _browser_modules: Dict[str, ModuleType] = {'chrome': chm,
17 | 'electron': ele,
18 | 'edge': edge,
19 | 'msie':ie}
20 |
21 |
22 | def _build_url_from_dict(page: Dict[str, str], options: OptionsDictT) -> str:
23 | scheme = page.get('scheme', 'http')
24 | host = page.get('host', 'localhost')
25 | port = page.get('port', options["port"])
26 | path = page.get('path', '')
27 | if not isinstance(port, (int, str)):
28 | raise TypeError("'port' option must be an integer")
29 | return '%s://%s:%d/%s' % (scheme, host, int(port), path)
30 |
31 |
32 | def _build_url_from_string(page: str, options: OptionsDictT) -> str:
33 | if not isinstance(options['port'], (int, str)):
34 | raise TypeError("'port' option must be an integer")
35 | base_url = 'http://%s:%d/' % (options['host'], int(options['port']))
36 | return base_url + page
37 |
38 |
39 | def _build_urls(start_pages: Iterable[Union[str, Dict[str, str]]], options: OptionsDictT) -> List[str]:
40 | urls: List[str] = []
41 |
42 | for page in start_pages:
43 | if isinstance(page, dict):
44 | url = _build_url_from_dict(page, options)
45 | else:
46 | url = _build_url_from_string(page, options)
47 | urls.append(url)
48 |
49 | return urls
50 |
51 |
52 | def open(start_pages: Iterable[Union[str, Dict[str, str]]], options: OptionsDictT) -> None:
53 | # Build full URLs for starting pages (including host and port)
54 | start_urls = _build_urls(start_pages, options)
55 |
56 | mode = options.get('mode')
57 | if not isinstance(mode, (str, type(None))) and mode is not False:
58 | raise TypeError("'mode' option must by either a string, False, or None")
59 | if mode is None or mode is False:
60 | # Don't open a browser
61 | pass
62 | elif mode == 'custom':
63 | # Just run whatever command the user provided
64 | if not isinstance(options['cmdline_args'], list):
65 | raise TypeError("'cmdline_args' option must be of type List[str]")
66 | sps.Popen(options['cmdline_args'],
67 | stdout=sps.PIPE, stderr=sps.PIPE, stdin=sps.PIPE)
68 | elif mode in _browser_modules:
69 | # Run with a specific browser
70 | browser_module = _browser_modules[mode]
71 | path = _browser_paths.get(mode)
72 | if path is None:
73 | # Don't know this browser's path, try and find it ourselves
74 | path = browser_module.find_path()
75 | _browser_paths[mode] = path
76 |
77 | if path is not None:
78 | browser_module.run(path, options, start_urls)
79 | else:
80 | raise EnvironmentError("Can't find %s installation" % browser_module.name)
81 | else:
82 | # Fall back to system default browser
83 | for url in start_urls:
84 | wbr.open(url)
85 |
86 |
87 | def set_path(browser_name: str, path: str) -> None:
88 | _browser_paths[browser_name] = path
89 |
90 |
91 | def get_path(browser_name: str) -> Optional[str]:
92 | return _browser_paths.get(browser_name)
93 |
94 |
--------------------------------------------------------------------------------
/eel/chrome.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import sys
3 | import os
4 | import subprocess as sps
5 | from shutil import which
6 | from typing import List, Optional
7 | from eel.types import OptionsDictT
8 |
9 | # Every browser specific module must define run(), find_path() and name like this
10 |
11 | name: str = 'Google Chrome/Chromium'
12 |
13 | def run(path: str, options: OptionsDictT, start_urls: List[str]) -> None:
14 | if not isinstance(options['cmdline_args'], list):
15 | raise TypeError("'cmdline_args' option must be of type List[str]")
16 | if options['app_mode']:
17 | for url in start_urls:
18 | sps.Popen([path, '--app=%s' % url] +
19 | options['cmdline_args'],
20 | stdout=sps.PIPE, stderr=sps.PIPE, stdin=sps.PIPE)
21 | else:
22 | args: List[str] = options['cmdline_args'] + start_urls
23 | sps.Popen([path, '--new-window'] + args,
24 | stdout=sps.PIPE, stderr=sys.stderr, stdin=sps.PIPE)
25 |
26 |
27 | def find_path() -> Optional[str]:
28 | if sys.platform in ['win32', 'win64']:
29 | return _find_chrome_win()
30 | elif sys.platform == 'darwin':
31 | return _find_chrome_mac() or _find_chromium_mac()
32 | elif sys.platform.startswith('linux'):
33 | return _find_chrome_linux()
34 | else:
35 | return None
36 |
37 |
38 | def _find_chrome_mac() -> Optional[str]:
39 | default_dir = r'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
40 | if os.path.exists(default_dir):
41 | return default_dir
42 | # use mdfind ci to locate Chrome in alternate locations and return the first one
43 | name = 'Google Chrome.app'
44 | alternate_dirs = [x for x in sps.check_output(["mdfind", name]).decode().split('\n') if x.endswith(name)]
45 | if len(alternate_dirs):
46 | return alternate_dirs[0] + '/Contents/MacOS/Google Chrome'
47 | return None
48 |
49 |
50 | def _find_chromium_mac() -> Optional[str]:
51 | default_dir = r'/Applications/Chromium.app/Contents/MacOS/Chromium'
52 | if os.path.exists(default_dir):
53 | return default_dir
54 | # use mdfind ci to locate Chromium in alternate locations and return the first one
55 | name = 'Chromium.app'
56 | alternate_dirs = [x for x in sps.check_output(["mdfind", name]).decode().split('\n') if x.endswith(name)]
57 | if len(alternate_dirs):
58 | return alternate_dirs[0] + '/Contents/MacOS/Chromium'
59 | return None
60 |
61 |
62 | def _find_chrome_linux() -> Optional[str]:
63 | chrome_names = ['chromium-browser',
64 | 'chromium',
65 | 'google-chrome',
66 | 'google-chrome-stable']
67 |
68 | for name in chrome_names:
69 | chrome = which(name)
70 | if chrome is not None:
71 | return chrome
72 | return None
73 |
74 |
75 | def _find_chrome_win() -> Optional[str]:
76 | import winreg as reg
77 | reg_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe'
78 | chrome_path: Optional[str] = None
79 |
80 | for install_type in reg.HKEY_CURRENT_USER, reg.HKEY_LOCAL_MACHINE:
81 | try:
82 | reg_key = reg.OpenKey(install_type, reg_path, 0, reg.KEY_READ)
83 | chrome_path = reg.QueryValue(reg_key, None)
84 | reg_key.Close()
85 | if not os.path.isfile(chrome_path):
86 | continue
87 | except WindowsError:
88 | chrome_path = None
89 | else:
90 | break
91 |
92 | return chrome_path
93 |
--------------------------------------------------------------------------------
/eel/edge.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import platform
3 | import subprocess as sps
4 | import sys
5 | from typing import List
6 |
7 | from eel.types import OptionsDictT
8 |
9 | name: str = 'Edge'
10 |
11 |
12 | def run(_path: str, options: OptionsDictT, start_urls: List[str]) -> None:
13 | if not isinstance(options['cmdline_args'], list):
14 | raise TypeError("'cmdline_args' option must be of type List[str]")
15 | args: List[str] = options['cmdline_args']
16 | if options['app_mode']:
17 | cmd = 'start msedge --app={} '.format(start_urls[0])
18 | cmd = cmd + (" ".join(args))
19 | sps.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=sps.PIPE, shell=True)
20 | else:
21 | cmd = "start msedge --new-window "+(" ".join(args)) +" "+(start_urls[0])
22 | sps.Popen(cmd,stdout=sys.stdout, stderr=sys.stderr, stdin=sps.PIPE, shell=True)
23 |
24 | def find_path() -> bool:
25 | if platform.system() == 'Windows':
26 | return True
27 |
28 | return False
29 |
--------------------------------------------------------------------------------
/eel/eel.js:
--------------------------------------------------------------------------------
1 | eel = {
2 | _host: window.location.origin,
3 |
4 | set_host: function (hostname) {
5 | eel._host = hostname
6 | },
7 |
8 | expose: function(f, name) {
9 | if(name === undefined){
10 | name = f.toString();
11 | let i = 'function '.length, j = name.indexOf('(');
12 | name = name.substring(i, j).trim();
13 | }
14 |
15 | eel._exposed_functions[name] = f;
16 | },
17 |
18 | guid: function() {
19 | return eel._guid;
20 | },
21 |
22 | // These get dynamically added by library when file is served
23 | /** _py_functions **/
24 | /** _start_geometry **/
25 |
26 | _guid: ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
27 | (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
28 | ),
29 |
30 | _exposed_functions: {},
31 |
32 | _mock_queue: [],
33 |
34 | _mock_py_functions: function() {
35 | for(let i = 0; i < eel._py_functions.length; i++) {
36 | let name = eel._py_functions[i];
37 | eel[name] = function() {
38 | let call_object = eel._call_object(name, arguments);
39 | eel._mock_queue.push(call_object);
40 | return eel._call_return(call_object);
41 | }
42 | }
43 | },
44 |
45 | _import_py_function: function(name) {
46 | let func_name = name;
47 | eel[name] = function() {
48 | let call_object = eel._call_object(func_name, arguments);
49 | eel._websocket.send(eel._toJSON(call_object));
50 | return eel._call_return(call_object);
51 | }
52 | },
53 |
54 | _call_number: 0,
55 |
56 | _call_return_callbacks: {},
57 |
58 | _call_object: function(name, args) {
59 | let arg_array = [];
60 | for(let i = 0; i < args.length; i++){
61 | arg_array.push(args[i]);
62 | }
63 |
64 | let call_id = (eel._call_number += 1) + Math.random();
65 | return {'call': call_id, 'name': name, 'args': arg_array};
66 | },
67 |
68 | _sleep: function(ms) {
69 | return new Promise(resolve => setTimeout(resolve, ms));
70 | },
71 |
72 | _toJSON: function(obj) {
73 | return JSON.stringify(obj, (k, v) => v === undefined ? null : v);
74 | },
75 |
76 | _call_return: function(call) {
77 | return function(callback = null) {
78 | if(callback != null) {
79 | eel._call_return_callbacks[call.call] = {resolve: callback};
80 | } else {
81 | return new Promise(function(resolve, reject) {
82 | eel._call_return_callbacks[call.call] = {resolve: resolve, reject: reject};
83 | });
84 | }
85 | }
86 | },
87 |
88 | _position_window: function(page) {
89 | let size = eel._start_geometry['default'].size;
90 | let position = eel._start_geometry['default'].position;
91 |
92 | if(page in eel._start_geometry.pages) {
93 | size = eel._start_geometry.pages[page].size;
94 | position = eel._start_geometry.pages[page].position;
95 | }
96 |
97 | if(size != null){
98 | window.resizeTo(size[0], size[1]);
99 | }
100 |
101 | if(position != null){
102 | window.moveTo(position[0], position[1]);
103 | }
104 | },
105 |
106 | _init: function() {
107 | eel._mock_py_functions();
108 |
109 | document.addEventListener("DOMContentLoaded", function(event) {
110 | let page = window.location.pathname.substring(1);
111 | eel._position_window(page);
112 |
113 | let websocket_addr = (eel._host + '/eel').replace('http', 'ws');
114 | websocket_addr += ('?page=' + page);
115 | eel._websocket = new WebSocket(websocket_addr);
116 |
117 | eel._websocket.onopen = function() {
118 | for(let i = 0; i < eel._py_functions.length; i++){
119 | let py_function = eel._py_functions[i];
120 | eel._import_py_function(py_function);
121 | }
122 |
123 | while(eel._mock_queue.length > 0) {
124 | let call = eel._mock_queue.shift();
125 | eel._websocket.send(eel._toJSON(call));
126 | }
127 | };
128 |
129 | eel._websocket.onmessage = function (e) {
130 | let message = JSON.parse(e.data);
131 | if(message.hasOwnProperty('call') ) {
132 | // Python making a function call into us
133 | if(message.name in eel._exposed_functions) {
134 | try {
135 | let return_val = eel._exposed_functions[message.name](...message.args);
136 | eel._websocket.send(eel._toJSON({'return': message.call, 'status':'ok', 'value': return_val}));
137 | } catch(err) {
138 | debugger
139 | eel._websocket.send(eel._toJSON(
140 | {'return': message.call,
141 | 'status':'error',
142 | 'error': err.message,
143 | 'stack': err.stack}));
144 | }
145 | }
146 | } else if(message.hasOwnProperty('return')) {
147 | // Python returning a value to us
148 | if(message['return'] in eel._call_return_callbacks) {
149 | if(message['status']==='ok'){
150 | eel._call_return_callbacks[message['return']].resolve(message.value);
151 | }
152 | else if(message['status']==='error' && eel._call_return_callbacks[message['return']].reject) {
153 | eel._call_return_callbacks[message['return']].reject(message['error']);
154 | }
155 | }
156 | } else {
157 | throw 'Invalid message ' + message;
158 | }
159 |
160 | };
161 | });
162 | }
163 | };
164 |
165 | eel._init();
166 |
167 | if(typeof require !== 'undefined'){
168 | // Avoid name collisions when using Electron, so jQuery etc work normally
169 | window.nodeRequire = require;
170 | delete window.require;
171 | delete window.exports;
172 | delete window.module;
173 | }
174 |
--------------------------------------------------------------------------------
/eel/electron.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | import sys
3 | import os
4 | import subprocess as sps
5 | from shutil import which
6 | from typing import List, Optional
7 |
8 | from eel.types import OptionsDictT
9 |
10 | name: str = 'Electron'
11 |
12 | def run(path: str, options: OptionsDictT, start_urls: List[str]) -> None:
13 | if not isinstance(options['cmdline_args'], list):
14 | raise TypeError("'cmdline_args' option must be of type List[str]")
15 | cmd = [path] + options['cmdline_args']
16 | cmd += ['.', ';'.join(start_urls)]
17 | sps.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=sps.PIPE)
18 |
19 |
20 | def find_path() -> Optional[str]:
21 | if sys.platform in ['win32', 'win64']:
22 | # It doesn't work well passing the .bat file to Popen, so we get the actual .exe
23 | bat_path = which('electron')
24 | if bat_path:
25 | return os.path.join(bat_path, r'..\node_modules\electron\dist\electron.exe')
26 | elif sys.platform in ['darwin', 'linux']:
27 | # This should work fine...
28 | return which('electron')
29 | return None
30 |
--------------------------------------------------------------------------------
/eel/msIE.py:
--------------------------------------------------------------------------------
1 | import platform
2 | import subprocess as sps
3 | import sys
4 | from typing import List
5 |
6 | from eel.types import OptionsDictT
7 |
8 | name: str = 'MSIE'
9 |
10 |
11 | def run(_path: str, options: OptionsDictT, start_urls: List[str]) -> None:
12 | cmd = 'start microsoft-edge:{}'.format(start_urls[0])
13 | sps.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr, stdin=sps.PIPE, shell=True)
14 |
15 |
16 | def find_path() -> bool:
17 | if platform.system() == 'Windows':
18 | return True
19 |
20 | return False
21 |
--------------------------------------------------------------------------------
/eel/py.typed:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/python-eel/Eel/41e2d8a9ac1696def4b4dd2c440fa85538a6d6df/eel/py.typed
--------------------------------------------------------------------------------
/eel/types.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | from typing import Union, Dict, List, Tuple, Callable, Optional, Any, TYPE_CHECKING
3 | from typing_extensions import Literal, TypedDict, TypeAlias
4 | from bottle import Bottle
5 |
6 | # This business is slightly awkward, but needed for backward compatibility,
7 | # because Python <3.10 doesn't support TypeAlias, jinja2 may not be available
8 | # at runtime, and geventwebsocket.websocket doesn't have type annotations so
9 | # that direct imports will raise an error.
10 | if TYPE_CHECKING:
11 | from jinja2 import Environment
12 | JinjaEnvironmentT: TypeAlias = Environment
13 | from geventwebsocket.websocket import WebSocket
14 | WebSocketT: TypeAlias = WebSocket
15 | else:
16 | JinjaEnvironmentT: TypeAlias = Any
17 | WebSocketT: TypeAlias = Any
18 |
19 | OptionsDictT = TypedDict(
20 | 'OptionsDictT',
21 | {
22 | 'mode': Optional[Union[str, Literal[False]]],
23 | 'host': str,
24 | 'port': int,
25 | 'block': bool,
26 | 'jinja_templates': Optional[str],
27 | 'cmdline_args': List[str],
28 | 'size': Optional[Tuple[int, int]],
29 | 'position': Optional[Tuple[int, int]],
30 | 'geometry': Dict[str, Tuple[int, int]],
31 | 'close_callback': Optional[Callable[..., Any]],
32 | 'app_mode': bool,
33 | 'all_interfaces': bool,
34 | 'disable_cache': bool,
35 | 'default_path': str,
36 | 'app': Bottle,
37 | 'shutdown_delay': float,
38 | 'suppress_error': bool,
39 | 'jinja_env': JinjaEnvironmentT,
40 | },
41 | total=False
42 | )
43 |
--------------------------------------------------------------------------------
/examples/01 - hello_world-Edge/hello.py:
--------------------------------------------------------------------------------
1 | import os
2 | import platform
3 | import sys
4 |
5 | # Use latest version of Eel from parent directory
6 | sys.path.insert(1, '../../')
7 | import eel
8 |
9 | # Use the same static files as the original Example
10 | os.chdir(os.path.join('..', '01 - hello_world'))
11 |
12 | # Set web files folder and optionally specify which file types to check for eel.expose()
13 | eel.init('web', allowed_extensions=['.js', '.html'])
14 |
15 |
16 | @eel.expose # Expose this function to Javascript
17 | def say_hello_py(x):
18 | print('Hello from %s' % x)
19 |
20 |
21 | say_hello_py('Python World!')
22 | eel.say_hello_js('Python World!') # Call a Javascript function
23 |
24 | # Launch example in Microsoft Edge only on Windows 10 and above
25 | if sys.platform in ['win32', 'win64'] and int(platform.release()) >= 10:
26 | eel.start('hello.html', mode='edge')
27 | else:
28 | raise EnvironmentError('Error: System is not Windows 10 or above')
29 |
30 | # # Launching Edge can also be gracefully handled as a fall back
31 | # try:
32 | # eel.start('hello.html', mode='chrome-app', size=(300, 200))
33 | # except EnvironmentError:
34 | # # If Chrome isn't found, fallback to Microsoft Edge on Win10 or greater
35 | # if sys.platform in ['win32', 'win64'] and int(platform.release()) >= 10:
36 | # eel.start('hello.html', mode='edge')
37 | # else:
38 | # raise
39 |
--------------------------------------------------------------------------------
/examples/01 - hello_world/hello.py:
--------------------------------------------------------------------------------
1 | import eel
2 |
3 | # Set web files folder
4 | eel.init('web')
5 |
6 | @eel.expose # Expose this function to Javascript
7 | def say_hello_py(x):
8 | print('Hello from %s' % x)
9 |
10 | say_hello_py('Python World!')
11 | eel.say_hello_js('Python World!') # Call a Javascript function
12 |
13 | eel.start('hello.html', size=(300, 200)) # Start
14 |
--------------------------------------------------------------------------------
/examples/01 - hello_world/web/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/python-eel/Eel/41e2d8a9ac1696def4b4dd2c440fa85538a6d6df/examples/01 - hello_world/web/favicon.ico
--------------------------------------------------------------------------------
/examples/01 - hello_world/web/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Hello, World!
5 |
6 |
7 |
8 |
19 |
20 |
21 |
22 | Hello, World!
23 |
24 |
--------------------------------------------------------------------------------
/examples/02 - callbacks/callbacks.py:
--------------------------------------------------------------------------------
1 | import eel
2 | import random
3 |
4 | eel.init('web')
5 |
6 | @eel.expose
7 | def py_random():
8 | return random.random()
9 |
10 | @eel.expose
11 | def py_exception(error):
12 | if error:
13 | raise ValueError("Test")
14 | else:
15 | return "No Error"
16 |
17 | def print_num(n):
18 | print('Got this from Javascript:', n)
19 |
20 |
21 | def print_num_failed(error, stack):
22 | print("This is an example of what javascript errors would look like:")
23 | print("\tError: ", error)
24 | print("\tStack: ", stack)
25 |
26 | # Call Javascript function, and pass explicit callback function
27 | eel.js_random()(print_num)
28 |
29 | # Do the same with an inline callback
30 | eel.js_random()(lambda n: print('Got this from Javascript:', n))
31 |
32 | # Show error handling
33 | eel.js_with_error()(print_num, print_num_failed)
34 |
35 |
36 | eel.start('callbacks.html', size=(400, 300))
37 |
38 |
--------------------------------------------------------------------------------
/examples/02 - callbacks/web/callbacks.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Callbacks Demo
5 |
6 |
7 |
49 |
50 |
51 |
52 | Callbacks demo
53 |
54 |
55 |
--------------------------------------------------------------------------------
/examples/02 - callbacks/web/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/python-eel/Eel/41e2d8a9ac1696def4b4dd2c440fa85538a6d6df/examples/02 - callbacks/web/favicon.ico
--------------------------------------------------------------------------------
/examples/03 - sync_callbacks/sync_callbacks.py:
--------------------------------------------------------------------------------
1 | import eel, random
2 |
3 | eel.init('web')
4 |
5 | @eel.expose
6 | def py_random():
7 | return random.random()
8 |
9 | eel.start('sync_callbacks.html', block=False, size=(400, 300))
10 |
11 | # Synchronous calls must happen after start() is called
12 |
13 | # Get result returned synchronously by
14 | # passing nothing in second brackets
15 | # v
16 | n = eel.js_random()()
17 | print('Got this from Javascript:', n)
18 |
19 | while True:
20 | eel.sleep(1.0)
21 |
--------------------------------------------------------------------------------
/examples/03 - sync_callbacks/web/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/python-eel/Eel/41e2d8a9ac1696def4b4dd2c440fa85538a6d6df/examples/03 - sync_callbacks/web/favicon.ico
--------------------------------------------------------------------------------
/examples/03 - sync_callbacks/web/sync_callbacks.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Synchronous callbacks
5 |
6 |
7 |
27 |
28 |
29 |
30 | Synchronous callbacks
31 |
32 |
--------------------------------------------------------------------------------
/examples/04 - file_access/README.md:
--------------------------------------------------------------------------------
1 | # Example 4 - file access
2 |
3 | 
4 |
--------------------------------------------------------------------------------
/examples/04 - file_access/Screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/python-eel/Eel/41e2d8a9ac1696def4b4dd2c440fa85538a6d6df/examples/04 - file_access/Screenshot.png
--------------------------------------------------------------------------------
/examples/04 - file_access/file_access.py:
--------------------------------------------------------------------------------
1 | import eel, os, random
2 |
3 | eel.init('web')
4 |
5 | @eel.expose
6 | def pick_file(folder):
7 | if os.path.isdir(folder):
8 | return random.choice(os.listdir(folder))
9 | else:
10 | return 'Not valid folder'
11 |
12 | eel.start('file_access.html', size=(320, 120))
13 |
--------------------------------------------------------------------------------
/examples/04 - file_access/web/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/python-eel/Eel/41e2d8a9ac1696def4b4dd2c440fa85538a6d6df/examples/04 - file_access/web/favicon.ico
--------------------------------------------------------------------------------
/examples/04 - file_access/web/file_access.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Eel Demo
5 |
6 |
18 |
19 |
20 |
21 |
25 |