Search code examples
pythonwindowsshebang

using #!/usr/bin/env python3 shebang with Windows


I'm trying to run a Python script from the command line as a command on Windows -- so no usage of "Python" or ".py". If my script is named "testing.py", I am attempting to make this name into a command and call "testing" from the command line.

Going through the docs it seems I need to use this shebang #!/usr/bin/env python as long as I have Python in my PATH.

https://docs.python.org/3/using/windows.html#shebang-lines

I also have the script folder in my PATH, so something like "testing.py" is currently working from the command line.

According to the docs and this tutorial, https://dbader.org/blog/how-to-make-command-line-commands-with-python

I should be able to evoke my Python script just by "testing" if I have the proper paths within PATH and the above shebang. However, I can't seem to get the script running withouth adding ".py".


Solution

  • No, Windows does not support shebang lines.

    The documentation you've linked relates to the py launcher installed by Python, which can interpret various shebang lines to choose a Python version to run a script with.

    setuptools is able to generate wrapper .exes for your Python scripts, but it gets a little involved and already assumes you have a package with a setup.py and so on.

    Locally, if you really, really need this, you probably could add .py to the PATHEXT environment variable, so the Windows command line looks up .pys like it looks up .exes (and various others; the current modern default is .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC). However, this will naturally not scale for distributing apps, as all of your users would need to set that too.

    My recommendation is to stick with just that boring old python testing.py, really.