Tuesday, February 02, 2021

Executing Python script directly within virtual environment from command line

Recently, I made a GUI for Google Translate's text-to-speech service. On my setup, I run it without a virtual environment. But this is actually a great tool, so I wanted to find a way to run it from the command line without having to install the required packages outside a virtual environment.

It turns out that it is actually very easy to directly run a Python script within a virtual environment from the command line. Just use the full path to the Python interpreter of the virtual environment to run the script.

For example, let's say my virtual environment is located at /home/user/venv and the script I want to run is at /home/user/gtts-gui/gtts-gui.py. To run this script, all I need to do is execute from the command line:
/home/user/venv/bin/python3 /home/user/gtts-gui/gtts-gui.py

You can even create a bash script with a name like gtts-gui and putting it somewhere in PATH.
#!/usr/bin/bash
/home/user/venv/bin/python3 /home/user/gtts-gui/gtts-gui.py

Use
chmod a+x gtts-gui
to make the script executable.

(Of course, /home/user can be replaced by the usual ~ tilde too.)

No comments: