Skip to content

Instantly share code, notes, and snippets.

@plembo
Last active November 5, 2021 23:26
Show Gist options
  • Save plembo/cf603342518b4321ecf4171629d5b9ba to your computer and use it in GitHub Desktop.
Save plembo/cf603342518b4321ecf4171629d5b9ba to your computer and use it in GitHub Desktop.
What shebang to use in for python script in a venv?

What path to use in the shebang (#!) for a python script in a venv?

In order to run a python script under bash and most other Unix or Linux systems without invoking the python executable manually, you need to include the python path in a "shebang" (#!) at the top of the script.

That's easy enough in a standard environment:

#!/usr/bin/python3

But in a python virtual environment (venv) that's going to be a problem because the binary will be "python", not "python3", and although the latest version of venv was designed to detect the default python binary in the environment, it's going to do as instructed if given told to use "python3" in the shebang.

The answer is to use the env utility to identify the python executable:

#!/usr/bin/env python

This is also what you'd do if you're using python on pyenv.

and then switch the name of the python binary as needed. And yes, this also works on Windows.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment