I would like to start a python script from a virtual environment on startup. I have searched the whole forum and other sources but have not been able to make it work.
The script should run at the scripts directory as working directory and also the terminal that started the script should be kept visible.
I have mainly used the "Startup Applications" and different configurations of .desktop files in ~/user/.config/autostart
I have tried with running shell files that work on their own as the below:
[Desktop Entry]
Type=Application
Terminal=true
Exec=/home/user/autostart.sh
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=True
Name=autostart_shell
Comment=
And the .sh-file
#!/usr/bin/env bash
sleep 10
cd /home/user/environment
bin/python3 main.py
bash
or something like this
#!/usr/bin/env bash
sleep 10
cd /home/user/environment
source bin/activate
python3 main.py
bash
However the environment never gets activated.
I have also tried other .desktop-configurations as below without success
[Desktop Entry]
Type=Application
Path=/home/user/env/
Terminal=true
Exec=gnome-terminal --command 'bash -ec "sleep 10;cd /home/user/env;source bin/activate;python3 main.py;bash"'
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
I've spent most of the day on this without any success, does anyone have any ideas?
UPDATE Ok, after some more work the problem is related to activating the virtual environment.
I'm using the "Startup Applications" to run a shell script. I have tried both the gnome-terminal and xterm with the same result. Below is the command in the *.desktop jobs
gnome-terminal --command '/home/user/folder/startup.sh'
and
xterm /home/user/folder/startup.sh
The shell script looks as follows:
#!/bin/bash
# Give it some time to make sure everything is loaded
sleep 5
# Logging to make sure it is run
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
echo "$TIMESTAMP - program was run " >> /home/user/folder/log.txt
# Switching working directory
cd /home/user/folder
# Alternative 1
# Run python script with virtual envirnments python binary
/home/user/folder/bin/python3 /home/user/folder/main.py
# Alternative 2
# Activate environment and then run
source /home/user/folder/bin/activate
python3 /home/user/folder/main.py
# Keep the terminal open
bash
On boot and login the terminal is launched but a python error is displayed about a missing module. If the shell script is run standalone it works without a problem, but launched from the "Startup applications" it is not.
This is nagging me so hard, is it really not possible to start a terminal in a python virtual environment?
you have to change the .sh-file to :
you miss a slash before bin/python3 , and python is not installed on the /bin directory , it is installed at /usr/bin directory