Python命令行-x选项

1 python windows python-2.7 python-3.x

我最近看到python将-x作为命令行选项,它在这里的文档中做了解释

python -x

Skip the first line of the source, allowing use of non-Unix forms of #!cmd. This is intended for a DOS specific hack only.
Run Code Online (Sandbox Code Playgroud)

但是,请原谅我:)我真的不明白为什么有人会使用非Unix形式的#!cmd,即使有人使用(对于DOS)为什么也要跳过它呢?

eph*_*ent 5

用第一行启动Windows批处理脚本(.bat/ .cmd):

@echo off & python -x "%~f0" %* & goto :eof
Run Code Online (Sandbox Code Playgroud)

当您运行它时,cmd.exe它将python -x以脚本的完整文件路径和其余命令行参数静默运行,然后忽略文件的其余部分。python将读取文件,跳过第一行(不会解析为Python代码),并将其余部分视为普通的Python脚本。

在类似UNIX的平台上,这不是必需的,因为

#!/usr/bin/env python
Run Code Online (Sandbox Code Playgroud)

在脚本的顶部获得类似的行为,这看起来像是对Python的注释,因此它可以在文件的其余部分继续执行。