Search code examples
pythonpackageshortcutpython-packaging

Executing python from a shortcut breaks its imports


I have a project where I have made some packages of my own. The project folder looks like this

Project
   - my_package
      __init__.py
      file1.py
      file2.py
   main.py

The main.py file has the line import my_package

The init.py file in my_package has these lines:

import sys
sys.path.insert(0, "my_package/")
from file1 import *
from file2 import *

If I cd to the main.py folder and run it, it works fine, but if I create a shortcut in my desktop and try to launch it, I get this error:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
  File "/home/kolterdyx/.local/lib/python3.8/site-packages/PyInstaller/loader/pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "my_package/__init__.py", line 3, in <module>
ModuleNotFoundError: No module named 'file1'
Traceback (most recent call last):
  File "main.py", line 6, in <module>
  File "/home/kolterdyx/.local/lib/python3.8/site-packages/PyInstaller/loader/pyimod03_importers.py", line 623, in exec_module
    exec(bytecode, module.__dict__)
  File "my_package/__init__.py", line 3, in <module>
ModuleNotFoundError: No module named 'file2'

This is my shortcut/launcher:

[Desktop Entry]
Version=0.0.1
Type=Application
Terminal=false
Exec=/home/kolterdyx/VoidShips/Launcher  #Launcher is a python script compiled with PyInstaller
Name=VoidShips

I guess this is because it tries to find file1.py and file2.py in the desktop and since they aren't it looks for python modules, and it does not find them.

How can I use a shortcut and still make the program run from its own directory?


Solution

  • Use relative imports:

    from .file1 import *
    from .file2 import *
    

    You can refer for example to this article for more information.