Let’s reiterate:
- The script works fine with
python .\myscript.py
in Powershell. - The script closes instantly without anything being done when double-clicking it.
- A smaller script you tested works both with the console and double click.
This means:
- The problem isn’t some exception thrown by your script.
- The problem isn’t in the binding of Python to the .py extension.
But it’s pretty hard to find out more when the script window isn’t open long enough to see anything.
So, try just executing .\myscript
(without python
) in Powershell. This is equivalent to double clicking, but shows all output/errors.
Does this give you something along the lines of Python could not be found.
?
If not, then hopefully the error shown will point you in the right direction.
If yes, you know this can’t really be true, as python .\myscript.py
works.
So, what is the problem?
Do you have a shebang line at the start of your in the script? Specifically, #!/usr/bin/env python3
?
Try removing it, see if it works then.
Explanation:
On Linux, shebang lines help the OS know which program to run when doing ./myscript.py
.
On Windows, the registry already does file association and the content of the file is only evaluated by the program specified there, so a shebang line isn’t strictly needed.
But, using the Python Launcher (py.exe
), which is associated for .py files when installing Python on Windows by default, shebangs are evaluated and can be used e.g. to choose different Python installations or support arguments (python -v .\myscript.exe
) on double click execution.
The problem is, if you use the wrong shebang, Python doesn’t know how to deal with that. #!/usr/bin/env python3
is such a wrong shebang.
This is because in Linux, env
is used similar to $Path
in Windows. So it’s a pointer to one “default” installation of Python. The advantage of using env
is that it’s independent from installation path. The disadvantage is, that there is only one default.
So, what does work?
In my testing, the following work on Windows:
#!/usr/bin/env python
(Best choice imo)#!/usr/bin/python
#!/usr/bin/python3
#! python