Shebang Notation: Python Scripts on Windows and Linux?

空扰寡人 提交于 2019-11-26 13:06:22
Spencer Rathbun

Unless you are using cygwin, windows has no shebang support. However, when you install python, it add as file association for .py files. If you put just the name of your script on the command line, or double click it in windows explorer, then it will run through python.

What I do is include a #!/usr/bin/env python shebang in my scripts. This allows for shebang support on linux. If you run it on a windows machine with python installed, then the file association should be there, and it will run as well.

Read up on the Python Launcher for Windows in the docs, which was initially described in PEP 397. It lets you define custom shebang configurations in an ini (e.g. to use pypy), but out of the box you can use virtual shebangs such as #!/usr/bin/env python3, or shebangs with real paths such as #!"C:\Python33\python.exe" (quoting is required for paths containing spaces). You can also add command-line options to a shebang. For example, the following shebang adds the option to enter interactive mode after the script terminates: #!/usr/bin/python3 -i.

Python 3.3 associates .py (console) and .pyw (GUI) script file types with the respectively named launchers, py.exe and pyw.exe, to enable shebang support for scripts on Windows. The new launchers are installed to the root Windows folder (i.e. %SystemRoot%) when installing for all users. Otherwise you'll want to add the installation directory to PATH in order to use py.exe in the shell. Then from the command line you can run py -2, py -3, py -2.6, py -3.3-32 (32-bit), and so on. The launcher is handy when combined with -m to run a module as a script, e.g. py -3 -m pip install.

There's also a version of pylauncher that can be installed separately if you only use Python 2.

Install pywin32. One of the nice thing is it setups the file association of *.py to the python interpreter.

Chris J

Not with shebang ... but you might be able to set up a file association, see this SO question which deals with Perl and the associated answers which will also be pertinent as there's known problems with Windows and stdin/out redirection...

sorry for open old topic.

I create one file py.cmd and place it in the C:\Windows\System32 folder

py.bat:

@(
@set /p shebang=
)<%1
@set shebang=%shebang:#! =%
@%shebang% %1 %2 %3 %4 %5 %6 %7 %8 %9

py.bat file explain:

  1. Get the first line from *.py file
  2. Remove shebang characters "#! "
  3. Run python file using shebang python path

All windows python script must start with shebang line as the first line in the code:

#! c:\Python27\python.exe

or

#! c:\Python37\python.exe

Then run it: cmd> py SomePyFile.py param1 param1 paramX

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!