mljar / mercury

Convert Jupyter Notebooks to Web Apps

Home Page:https://RunMercury.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to import a python file

spqw opened this issue · comments

What is the issue

Importing a python file works in a jupyter notebook but does not seem to work ina mercury app.

Screenshot 2024-01-05 at 11 08 57

How to reproduce it

Screenshot 2024-01-05 at 11 10 18
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3fbc5f1-47f6-4bc6-a5fa-e49be21d318e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from utils import foo\n",
    "import mercury as mr # for widgets\n",
    "import random # for random data generation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c73613d3-a731-4ac4-91d3-e97944f9094a",
   "metadata": {},
   "outputs": [],
   "source": [
    "app = mr.App(title=\"Hello in Mercury!\", description=\"Samples app in Mercury\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "abdce55e-a9b6-4f1d-904f-ce3e45db6ed9",
   "metadata": {},
   "outputs": [],
   "source": [
    "name = mr.Text(label=\"What is your name?\", value=\"Piotr\")\n",
    "points = mr.Slider(label=\"Number of points\", value=75, min=50, max=100)\n",
    "color = mr.Select(label=\"Select color\", value=\"blue\", choices=[\"red\", \"green\", \"blue\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78390e05-166f-49cd-a956-e7aa4bfd7a2d",
   "metadata": {},
   "outputs": [],
   "source": [
    "mr.Md(f\"\"\"## How are you {name.value}?\n",
    "You can mix Python code and Markdown.\"\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "04b1c8c5-af04-4b32-afe2-0d8a193d0037",
   "metadata": {},
   "outputs": [],
   "source": [
    "foo()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "mercury-py311",
   "language": "python",
   "name": "mercury-py311"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
Screenshot 2024-01-05 at 11 10 14
import mercury as mr
def foo():
    print("Hello from foo")
    mr.Md("Hello from foo!")

Hi,
The issue could be because of relative paths. At the beginning of the notebook, try setting the paths like

import sys
sys.path.append(path)

where the path could be an absolute path to the python file or the folder containing __init__.py.
I hope this helps.

I think the directory is /app/yourpythonfile.py if its in the same directory as your notebook