Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5288

Python • Re: Multiple python scripts in virtual environment

$
0
0
I have been using python scripts successfully for a few years but recently upgraded to Pi5 running bookworm. The virtual environment that python uses now proved to be a hurdle but I think that I got it figured out after several days of experimenting and searching. the web. Given that, I have a couple of questions to which I haven't found the answer. My pi5 runs some python scripts to collect various bits of data and perform tasks throughout the day and night i.e. backup, collect room temperatures, perform speed tests for internet connection health, etc. All of the scripts are started via cron and then stopped until the next call from cron.

Should each script run in it's own virtual environment or should I have only only ONE virtual environment in which all of the scripts run?

That's entirely up to you. It also depends on which modules your scripts need and whether those modules are the same version.

If you've not needed to install any modules with pip or pip3 you don't need a venv.
I have figured out how to start scripts using this in a bash shell script:

Code:

source /path/to/venv/activate && /path/to/script.py

An alternative is

Code:

/path/to/venv/bin/python /path/to/script.py
Python will detect the venv and use it with the need for manual activation. That also means it will only impact the particular python script you are running.
Should the virtual environment be deactivated at the completion of each script? And is so, how would I deactivate the environment at the end of the script?

In the case of cron, each job runs in its own shell. When the job finishes the shell is closed so there is no need to deactivate the venv.

Statistics: Posted by thagrol — Sun Dec 08, 2024 1:33 pm



Viewing all articles
Browse latest Browse all 5288

Trending Articles