# Eel
[![PyPI version](https://img.shields.io/pypi/v/Eel?style=for-the-badge)](https://pypi.org/project/Eel/)
[![PyPi Downloads](https://img.shields.io/pypi/dm/Eel?style=for-the-badge)](https://pypistats.org/packages/eel)
![Python](https://img.shields.io/pypi/pyversions/Eel?style=for-the-badge)
[![License](https://img.shields.io/pypi/l/Eel.svg?style=for-the-badge)](https://pypi.org/project/Eel/)
Eel is a little Python library for making simple Electron-like offline HTML/JS GUI apps, with full access to Python capabilities and libraries.
> **Eel hosts a local webserver, then lets you annotate functions in Python so that they can be called from Javascript, and vice versa.**
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).
<p align="center"><img src="https://raw.githubusercontent.com/samuelhwilliams/Eel/master/examples/04%20-%20file_access/Screenshot.png" ></p>
<!-- TOC -->
- [Eel](#eel)
- [Intro](#intro)
- [Install](#install)
- [Usage](#usage)
- [Directory Structure](#directory-structure)
- [Starting the app](#starting-the-app)
- [App options](#app-options)
- [Chrome/Chromium flags](#chromechromium-flags)
- [Exposing functions](#exposing-functions)
- [Eello, World!](#eello-world)
- [Return values](#return-values)
- [Callbacks](#callbacks)
- [Synchronous returns](#synchronous-returns)
- [Asynchronous Python](#asynchronous-python)
- [Building distributable binary with PyInstaller](#building-distributable-binary-with-pyinstaller)
- [Microsoft Edge](#microsoft-edge)
<!-- /TOC -->
## Intro
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.
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.
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.
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.
Join Eel's users and maintainers on [Discord](https://discord.com/invite/3nqXPFX), if you like.
## Install
Install from pypi with `pip`:
```shell
pip install eel
```
To include support for HTML templating, currently using [Jinja2](https://pypi.org/project/Jinja2/#description):
```shell
pip install eel[jinja2]
```
## Usage
### Directory Structure
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.
All the frontend files should be put in a single directory (they can be further divided into folders inside this if necessary).
```
my_python_script.py <-- Python scripts
other_python_module.py
static_web_folder/ <-- Web folder
main_page.html
css/
style.css
img/
logo.png
```
### Starting the app
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;
```python
import eel
eel.init('web')
eel.start('main.html')
```
This will start a webserver on the default settings (http://localhost:8000) and open a browser to http://localhost:8000/main.html.
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).
### App options
Additional options can be passed to `eel.start()` as keyword arguments.
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.
As of Eel v0.12.0, the following options are available to `start()`:
- **mode**, a string specifying what browser to use (e.g. `'chrome'`, `'electron'`, `'edge'`, `'custom'`). Can also be `None` or `False` to not open a window. *Default: `'chrome'`*
- **host**, a string specifying what hostname to use for the Bottle server. *Default: `'localhost'`)*
- **port**, an int specifying what port to use for the Bottle server. Use `0` for port to be picked automatically. *Default: `8000`*.
- **block**, a bool saying whether or not the call to `start()` should block the calling thread. *Default: `True`*
- **jinja_templates**, a string specifying a folder to use for Jinja2 templates, e.g. `my_templates`. *Default: `None`*
- **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: `[]`*
- **size**, a tuple of ints specifying the (width, height) of the main window in pixels *Default: `None`*
- **position**, a tuple of ints specifying the (left, top) of the main window in pixels *Default: `None`*
- **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: {}*
- **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`*
- **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.
- **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
### Exposing functions
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:
```html
<script type="text/javascript" src="/eel.js"></script>
```
Including this library creates an `eel` object which can be used to communicate with the Python side.
Any functions in the Python code which are decorated with `@eel.expose` like this...
```python
@eel.expose
def my_python_function(a, b):
print(a, b, a + b)
```
...will appear as methods on the `eel` object on the Javascript side, like this...
```javascript
console.log("Calling Python...");
eel.my_python_function(1, 2); // This calls the Python function that was decorated
```
Similarly, any Javascript functions which are exposed like this...
```javascript
eel.expose(my_javascript_function);
function my_javascript_function(a, b, c, d) {
if (a < b) {
console.log(c * d);
}
}
```
can be called from the Python side like this...
```python
print('Calling Javascript...')
eel.my_javascript_function(1, 2, 3, 4) # This calls the Javascript function
```
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:
```javascript
eel.expose(someFunction, "my_javascript_function");
```
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).
### Eello, World!
> See full example in: [examples/01 - hello_world](https://github.com/ChrisKnott/Eel/tree/master/examples/01%20-%20hello_world)
Putting this together into a **Hello, World!** example, we have a short HTML page, `web/hello.html`:
```html
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
<!-- Include eel.js - note this file doesn't exist in the 'web' directory -->
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript">
eel.expose(say_hello_js); // Expose this function to Python
function say_hello_js(x) {
console.log("Hello from " + x);
}
say_hello_js("Javascript World!");
eel.say_hello_py("Javascript World!"); // Call a Python function
</script>
</head>
<body>
Hello, World!
</body>
</html>
```
and a short Python script `hello.py`:
```python
import eel
# Set web files folder and optionally specify which file types to check for eel.expose()
# *Default allowed_extensions are: ['.js', '.html', '.txt', '.htm', '.xhtml']
eel.init('web', allowed_extensions=['.js', '.html'])
@eel.expose # Expose this function to Javascript
def say_hello_py(x):
print('Hello from %s' % x)
say_hello_py('Python World!')
eel.say_hello_js('Python World!') # Call a Javascript function
eel.start('hello.html') # Start (this blocks and enters loop)
```
If we run the Python script (`python hello.py`), then a browser window will open displaying `hello.html`, and we will see...
```
Hello from Python World!
Hello from Javascript World!
```
...in the terminal, and...
```
Hello from Javascript World!
Hello from Python World!
```
...in the browser console (press F12 to open).
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.
### Return values
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.
Eel supports two ways of retrieving _return values_ from the other side of the app, which helps keep the code concise.
To prevent hanging forever on the Python side, a timeout has been put in place for trying to retrieve values from
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.
#### Callbacks
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.
For example, if we have the following function defined and exposed in Javascript:
```javascript
eel.expose(js_random);
function js_random() {
return Math.random();
}
```
Then in Python we can retrieve random values from the Javascript side like so:
```python
def print_num(n):
print('Got this from Javascript:', n)
# Call Javascript function, and pass explicit callback function
eel.js_random()(print_num)
# Do the same with an inline lambda as callback
eel.js_random()(lambda n: print('Got this from Javascript:', n))
```
(It works exactly the same the other way around).
#### Synchronous returns
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.
To synchronously retrieve the return value, simply pass nothing to the second set of brackets. So in Python we would write:
```python
n = eel.js_random()() # This immediately returns the value
print('Got this from Javascript:', n)
```
You can only perform synchronous returns after the browser window has started (after calling `eel.start()`), otherwise obviously the call will hang.
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:
```javascript
async function run() {
// Inside a function marked 'async' we can use the 'await' keyword.
let n = await eel.py_random()(); // Must prefix call with 'await', otherwise it's the same syntax
console.log("Got this from Python: " + n);
}
run();
```
## Asynchronous Python
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.
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).
In this example...
```python
import eel
eel.init('web')
def my_other_thread():
while True:
print("I'm a thread")
eel.sleep(1.0) # Use eel.sleep(), not time.sleep()
eel.spawn(my_other_thread)
eel.start('main.html', block=False) # Don't block on this call
while True:
print("I'm a main loop")
eel.sleep(1.0) # Use eel.sleep(), not time.sleep()
```
...we would then have three "threads" (greenlets) running;
1. Eel's internal thread for serving the web folder
2. The `my_other_thread` method, repeatedly printing **"I'm a thread"**
3. The main Python thread, which would be stuck in the final `while` loop, repeatedly printing **"I'm a main loop"**
## Building distributable binary with PyInstaller
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**.
1. Configure a virtualenv with desired Python version and minimum necessary Python packages
2. Install PyInstaller `pip install PyInstaller`
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`)
4. This will create a new folder `dist/`
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`
6. When happy that your app is working correctly, add `--onefile --noconsole` flags to build a single executable file
Consult the [documentation for PyInstaller](http://PyInstaller.readthedocs.io/en/stable/) for more options.
## Microsoft Edge
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:
- 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)
- Example implementing browser-fallbacks: [examples/07 - CreateReactApp/eel_CRA.py](https://github.com/ChrisKnott/Eel/tree/master/examples/07%20-%20CreateReactApp/eel_CRA.py)
Raw data
{
"_id": null,
"home_page": "https://github.com/gurjarms/eel",
"name": "Eel-n",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "gui, html, javascript, electron",
"author": "Gurjar mahi",
"author_email": "python-eel@protonmail.com",
"download_url": "https://files.pythonhosted.org/packages/22/ca/d431e934c4df1be627747c5d0b08dc4f6ab255ee677f2c7ac0cb75bf49e8/eel_n-0.16.0.tar.gz",
"platform": null,
"description": "# Eel\r\n\r\n[![PyPI version](https://img.shields.io/pypi/v/Eel?style=for-the-badge)](https://pypi.org/project/Eel/)\r\n[![PyPi Downloads](https://img.shields.io/pypi/dm/Eel?style=for-the-badge)](https://pypistats.org/packages/eel)\r\n![Python](https://img.shields.io/pypi/pyversions/Eel?style=for-the-badge)\r\n[![License](https://img.shields.io/pypi/l/Eel.svg?style=for-the-badge)](https://pypi.org/project/Eel/)\r\n\r\nEel is a little Python library for making simple Electron-like offline HTML/JS GUI apps, with full access to Python capabilities and libraries.\r\n\r\n> **Eel hosts a local webserver, then lets you annotate functions in Python so that they can be called from Javascript, and vice versa.**\r\n\r\nEel 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).\r\n\r\n<p align=\"center\"><img src=\"https://raw.githubusercontent.com/samuelhwilliams/Eel/master/examples/04%20-%20file_access/Screenshot.png\" ></p>\r\n\r\n<!-- TOC -->\r\n\r\n- [Eel](#eel)\r\n - [Intro](#intro)\r\n - [Install](#install)\r\n - [Usage](#usage)\r\n - [Directory Structure](#directory-structure)\r\n - [Starting the app](#starting-the-app)\r\n - [App options](#app-options)\r\n - [Chrome/Chromium flags](#chromechromium-flags)\r\n - [Exposing functions](#exposing-functions)\r\n - [Eello, World!](#eello-world)\r\n - [Return values](#return-values)\r\n - [Callbacks](#callbacks)\r\n - [Synchronous returns](#synchronous-returns)\r\n - [Asynchronous Python](#asynchronous-python)\r\n - [Building distributable binary with PyInstaller](#building-distributable-binary-with-pyinstaller)\r\n - [Microsoft Edge](#microsoft-edge)\r\n\r\n<!-- /TOC -->\r\n\r\n## Intro\r\n\r\nThere 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.\r\n\r\nThe 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.\r\n\r\nEel 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.\r\n\r\nFor 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.\r\n\r\nJoin Eel's users and maintainers on [Discord](https://discord.com/invite/3nqXPFX), if you like.\r\n\r\n## Install\r\n\r\nInstall from pypi with `pip`:\r\n\r\n```shell\r\npip install eel\r\n```\r\n\r\nTo include support for HTML templating, currently using [Jinja2](https://pypi.org/project/Jinja2/#description):\r\n\r\n```shell\r\npip install eel[jinja2]\r\n```\r\n\r\n## Usage\r\n\r\n### Directory Structure\r\n\r\nAn 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.\r\n\r\nAll the frontend files should be put in a single directory (they can be further divided into folders inside this if necessary).\r\n\r\n```\r\nmy_python_script.py <-- Python scripts\r\nother_python_module.py\r\nstatic_web_folder/ <-- Web folder\r\n main_page.html\r\n css/\r\n style.css\r\n img/\r\n logo.png\r\n```\r\n\r\n### Starting the app\r\n\r\nSuppose you put all the frontend files in a directory called `web`, including your start page `main.html`, then the app is started like this;\r\n\r\n```python\r\nimport eel\r\neel.init('web')\r\neel.start('main.html')\r\n```\r\n\r\nThis will start a webserver on the default settings (http://localhost:8000) and open a browser to http://localhost:8000/main.html.\r\n\r\nIf 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).\r\n\r\n### App options\r\n\r\nAdditional options can be passed to `eel.start()` as keyword arguments.\r\n\r\nSome 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.\r\n\r\nAs of Eel v0.12.0, the following options are available to `start()`:\r\n - **mode**, a string specifying what browser to use (e.g. `'chrome'`, `'electron'`, `'edge'`, `'custom'`). Can also be `None` or `False` to not open a window. *Default: `'chrome'`*\r\n - **host**, a string specifying what hostname to use for the Bottle server. *Default: `'localhost'`)*\r\n - **port**, an int specifying what port to use for the Bottle server. Use `0` for port to be picked automatically. *Default: `8000`*.\r\n - **block**, a bool saying whether or not the call to `start()` should block the calling thread. *Default: `True`*\r\n - **jinja_templates**, a string specifying a folder to use for Jinja2 templates, e.g. `my_templates`. *Default: `None`*\r\n - **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: `[]`*\r\n - **size**, a tuple of ints specifying the (width, height) of the main window in pixels *Default: `None`*\r\n - **position**, a tuple of ints specifying the (left, top) of the main window in pixels *Default: `None`*\r\n - **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: {}*\r\n - **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`*\r\n - **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.\r\n - **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\r\n\r\n\r\n\r\n### Exposing functions\r\n\r\nIn addition to the files in the frontend folder, a Javascript library will be served at `/eel.js`. You should include this in any pages:\r\n\r\n```html\r\n<script type=\"text/javascript\" src=\"/eel.js\"></script>\r\n```\r\n\r\nIncluding this library creates an `eel` object which can be used to communicate with the Python side.\r\n\r\nAny functions in the Python code which are decorated with `@eel.expose` like this...\r\n\r\n```python\r\n@eel.expose\r\ndef my_python_function(a, b):\r\n print(a, b, a + b)\r\n```\r\n\r\n...will appear as methods on the `eel` object on the Javascript side, like this...\r\n\r\n```javascript\r\nconsole.log(\"Calling Python...\");\r\neel.my_python_function(1, 2); // This calls the Python function that was decorated\r\n```\r\n\r\nSimilarly, any Javascript functions which are exposed like this...\r\n\r\n```javascript\r\neel.expose(my_javascript_function);\r\nfunction my_javascript_function(a, b, c, d) {\r\n if (a < b) {\r\n console.log(c * d);\r\n }\r\n}\r\n```\r\n\r\ncan be called from the Python side like this...\r\n\r\n```python\r\nprint('Calling Javascript...')\r\neel.my_javascript_function(1, 2, 3, 4) # This calls the Javascript function\r\n```\r\n\r\nThe 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:\r\n\r\n```javascript\r\neel.expose(someFunction, \"my_javascript_function\");\r\n```\r\n\r\nWhen 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).\r\n\r\n### Eello, World!\r\n\r\n> See full example in: [examples/01 - hello_world](https://github.com/ChrisKnott/Eel/tree/master/examples/01%20-%20hello_world)\r\n\r\nPutting this together into a **Hello, World!** example, we have a short HTML page, `web/hello.html`:\r\n\r\n```html\r\n<!DOCTYPE html>\r\n<html>\r\n <head>\r\n <title>Hello, World!</title>\r\n\r\n <!-- Include eel.js - note this file doesn't exist in the 'web' directory -->\r\n <script type=\"text/javascript\" src=\"/eel.js\"></script>\r\n <script type=\"text/javascript\">\r\n eel.expose(say_hello_js); // Expose this function to Python\r\n function say_hello_js(x) {\r\n console.log(\"Hello from \" + x);\r\n }\r\n\r\n say_hello_js(\"Javascript World!\");\r\n eel.say_hello_py(\"Javascript World!\"); // Call a Python function\r\n </script>\r\n </head>\r\n\r\n <body>\r\n Hello, World!\r\n </body>\r\n</html>\r\n```\r\n\r\nand a short Python script `hello.py`:\r\n\r\n```python\r\nimport eel\r\n\r\n# Set web files folder and optionally specify which file types to check for eel.expose()\r\n# *Default allowed_extensions are: ['.js', '.html', '.txt', '.htm', '.xhtml']\r\neel.init('web', allowed_extensions=['.js', '.html'])\r\n\r\n@eel.expose # Expose this function to Javascript\r\ndef say_hello_py(x):\r\n print('Hello from %s' % x)\r\n\r\nsay_hello_py('Python World!')\r\neel.say_hello_js('Python World!') # Call a Javascript function\r\n\r\neel.start('hello.html') # Start (this blocks and enters loop)\r\n```\r\n\r\nIf we run the Python script (`python hello.py`), then a browser window will open displaying `hello.html`, and we will see...\r\n\r\n```\r\nHello from Python World!\r\nHello from Javascript World!\r\n```\r\n\r\n...in the terminal, and...\r\n\r\n```\r\nHello from Javascript World!\r\nHello from Python World!\r\n```\r\n\r\n...in the browser console (press F12 to open).\r\n\r\nYou 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.\r\n\r\n### Return values\r\n\r\nWhile 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.\r\n\r\nEel supports two ways of retrieving _return values_ from the other side of the app, which helps keep the code concise.\r\n\r\nTo prevent hanging forever on the Python side, a timeout has been put in place for trying to retrieve values from\r\nthe 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.\r\n\r\n#### Callbacks\r\n\r\nWhen 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.\r\n\r\nFor example, if we have the following function defined and exposed in Javascript:\r\n\r\n```javascript\r\neel.expose(js_random);\r\nfunction js_random() {\r\n return Math.random();\r\n}\r\n```\r\n\r\nThen in Python we can retrieve random values from the Javascript side like so:\r\n\r\n```python\r\ndef print_num(n):\r\n print('Got this from Javascript:', n)\r\n\r\n# Call Javascript function, and pass explicit callback function\r\neel.js_random()(print_num)\r\n\r\n# Do the same with an inline lambda as callback\r\neel.js_random()(lambda n: print('Got this from Javascript:', n))\r\n```\r\n\r\n(It works exactly the same the other way around).\r\n\r\n#### Synchronous returns\r\n\r\nIn 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.\r\n\r\nTo synchronously retrieve the return value, simply pass nothing to the second set of brackets. So in Python we would write:\r\n\r\n```python\r\nn = eel.js_random()() # This immediately returns the value\r\nprint('Got this from Javascript:', n)\r\n```\r\n\r\nYou can only perform synchronous returns after the browser window has started (after calling `eel.start()`), otherwise obviously the call will hang.\r\n\r\nIn 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:\r\n\r\n```javascript\r\nasync function run() {\r\n // Inside a function marked 'async' we can use the 'await' keyword.\r\n\r\n let n = await eel.py_random()(); // Must prefix call with 'await', otherwise it's the same syntax\r\n console.log(\"Got this from Python: \" + n);\r\n}\r\n\r\nrun();\r\n```\r\n\r\n## Asynchronous Python\r\n\r\nEel 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.\r\n\r\nFor 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).\r\n\r\nIn this example...\r\n\r\n```python\r\nimport eel\r\neel.init('web')\r\n\r\ndef my_other_thread():\r\n while True:\r\n print(\"I'm a thread\")\r\n eel.sleep(1.0) # Use eel.sleep(), not time.sleep()\r\n\r\neel.spawn(my_other_thread)\r\n\r\neel.start('main.html', block=False) # Don't block on this call\r\n\r\nwhile True:\r\n print(\"I'm a main loop\")\r\n eel.sleep(1.0) # Use eel.sleep(), not time.sleep()\r\n```\r\n\r\n...we would then have three \"threads\" (greenlets) running;\r\n\r\n1. Eel's internal thread for serving the web folder\r\n2. The `my_other_thread` method, repeatedly printing **\"I'm a thread\"**\r\n3. The main Python thread, which would be stuck in the final `while` loop, repeatedly printing **\"I'm a main loop\"**\r\n\r\n## Building distributable binary with PyInstaller\r\n\r\nIf 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**.\r\n\r\n1. Configure a virtualenv with desired Python version and minimum necessary Python packages\r\n2. Install PyInstaller `pip install PyInstaller`\r\n3. 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`)\r\n4. This will create a new folder `dist/`\r\n5. 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`\r\n6. When happy that your app is working correctly, add `--onefile --noconsole` flags to build a single executable file\r\n\r\nConsult the [documentation for PyInstaller](http://PyInstaller.readthedocs.io/en/stable/) for more options.\r\n\r\n## Microsoft Edge\r\n\r\nFor 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:\r\n\r\n- 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)\r\n- Example implementing browser-fallbacks: [examples/07 - CreateReactApp/eel_CRA.py](https://github.com/ChrisKnott/Eel/tree/master/examples/07%20-%20CreateReactApp/eel_CRA.py)\r\n",
"bugtrack_url": null,
"license": null,
"summary": "For little HTML GUI applications, with easy Python/JS interop",
"version": "0.16.0",
"project_urls": {
"Homepage": "https://github.com/gurjarms/eel"
},
"split_keywords": [
"gui",
" html",
" javascript",
" electron"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "b55bb1fc36206ddc02785f10c23a626d8f09ecf91f30c0dcacffb60270a6cde6",
"md5": "c19b847b343dedc7079ef4678585d205",
"sha256": "c7dc4ae241df3ee647f2e3db2102df9f97edc3ee3676642483aa06caa0821dd4"
},
"downloads": -1,
"filename": "Eel_n-0.16.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "c19b847b343dedc7079ef4678585d205",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 19020,
"upload_time": "2024-07-11T16:20:56",
"upload_time_iso_8601": "2024-07-11T16:20:56.701917Z",
"url": "https://files.pythonhosted.org/packages/b5/5b/b1fc36206ddc02785f10c23a626d8f09ecf91f30c0dcacffb60270a6cde6/Eel_n-0.16.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "22cad431e934c4df1be627747c5d0b08dc4f6ab255ee677f2c7ac0cb75bf49e8",
"md5": "0b1a0a53eb735e6c971973dfbee005d0",
"sha256": "8234df3f1564b716d0ea82a3e31525e8d9502c2392afa730c6896928d2556bbb"
},
"downloads": -1,
"filename": "eel_n-0.16.0.tar.gz",
"has_sig": false,
"md5_digest": "0b1a0a53eb735e6c971973dfbee005d0",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 23098,
"upload_time": "2024-07-11T16:20:59",
"upload_time_iso_8601": "2024-07-11T16:20:59.906874Z",
"url": "https://files.pythonhosted.org/packages/22/ca/d431e934c4df1be627747c5d0b08dc4f6ab255ee677f2c7ac0cb75bf49e8/eel_n-0.16.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-07-11 16:20:59",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "gurjarms",
"github_project": "eel",
"travis_ci": true,
"coveralls": false,
"github_actions": false,
"requirements": [
{
"name": "bottle",
"specs": [
[
"<",
"1.0.0"
]
]
},
{
"name": "bottle-websocket",
"specs": [
[
"<",
"1.0.0"
]
]
},
{
"name": "gevent",
"specs": []
},
{
"name": "gevent-websocket",
"specs": [
[
"<",
"1.0.0"
]
]
},
{
"name": "greenlet",
"specs": [
[
"<",
"2.0.0"
],
[
">=",
"1.0.0"
]
]
},
{
"name": "pyparsing",
"specs": [
[
"<",
"4.0.0"
],
[
">=",
"3.0.0"
]
]
},
{
"name": "whichcraft",
"specs": [
[
"~=",
"0.4.1"
]
]
}
],
"tox": true,
"lcname": "eel-n"
}