I frequently find myself accidentally running python files as shell scripts, e.g. $ ./test.py

This has potential to cause lots of damage if there was no shebang line at the start of the file, so I would like a way for zsh to give a warning for doing this.

Does this functionality already exist somewhere?

If not, I'm thinking of using accept-line to implement this, but this seems like a catch-all solution, is there a more specific way?


You can use suffix aliases to ensure that .py files are run by python:

alias -s py='/usr/bin/env python'

When you now type command that ends in .py on your command line, it will be run with /usr/bin/env python.

Note: this does not care whether the file is executable or not. If you want to restrict this to executable .py files, you can use a function:

runxpy () {
    if [[ -x "$1" ]] ; then
        /usr/bin/env python "$@"
alias -s py=runxpy

One restriction is of course that the files in question have to have the .py suffix. Another is that any existing #!-line is ignored, but this could be solved by extending runxpy to parse the first line instead of just using /usr/bin/python every time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.