/assets/docker.png

How to use Python from Docker

Motivation

Sometimes you need to call scripts used by software you don’t have installed on your device. For me this was a python script. I’m not using python by any means and I’m not a great fan. So that’s why I didn’t like the idea of installing it just for this purpose. What I like though are containers, especially Docker is very enjoyable to use on a every day basis. So be sure to check this out, I mean you need it for what I’m about to show you any way so:

I do use Docker on my Windows PC from inside my WSL2, based on Ubuntu 20.04. This can be a little tricky to set up. So if you have any difficulties you can reach out to their respective GitHub or, ofcourse, StackOverflow.

How to run a Python script using Docker

To make it short, for ubuntu I am using the bash_alias below.

bash
# ~/.bash_aliases
alias python3='docker run -it --rm --name my-running-script --entrypoint python -v "$PWD":/usr/src/myapp -w /usr/src/myapp python:3'

After you added the shown line to your bash_aliases file in your home directory you can run

bash
source ~/.bash_aliases

which will enable you to use python3 globally. So to test this we can create a python script:

python
// my_script.py
print("This line will be printed.")

Having this script we are now able to run

Additional Tips

You can modify this Docker snippet to run other software like python2, caddy, nodejs, deno or whatever as well. In most cases it’s only necessary to change the image at the end from, for example, python:3 to caddy.

I hope you enjoyed this little tipp and can make good use of it as I did.