Skip to main content
 首页 » 编程设计

python之用于 Python 脚本的可移植 exe 包装器。在什么情况下我的解决方案不起作用

2025年05月04日1098°冷暖

我有这些 Python 2 和 3 脚本的包装器:

对于类 Unix 系统:

#!/bin/sh 
SCRIPTDIR="$(cd "$(dirname "$0")" && pwd)" 
/usr/bin/env python2.7 "$SCRIPTDIR/program27.py" "$@" 
 
#!/bin/sh 
SCRIPTDIR="$(cd "$(dirname "$0")" && pwd)" 
/usr/bin/env python3 "$SCRIPTDIR/program34.py" "$@" 

对于 Windows:

@py -2 "%~dp0\program27.py" %* 
 
@py -3 "%~dp0\program34.py" %* 

脚本是严格的命令行工具,它们始终与包装器放在同一目录中。脚本中也有版本检查。我基本上是在尝试确保使用正确的 Python 调用它们,并确保它们在尽可能多的系统和 Python 发行版上运行。

上面的包装器是我发现的唯一可以在 Windows、Linux 和 Cygwin 以及 Darwin(可能还有 BSD)上使用标准 Python 发行版的包装器。

我是这些东西的初学者,我知道没有完美的解决方案,所以我想知道是否有人可以指出上述方法在哪些情况下不起作用,并帮助我改进它。

谢谢。

请您参考如下方法:

请参阅PEP 397有关如何在 Windows 上正确的 Python 解释器中处理执行代码的信息。另一方面,PEP 394在类 Unix 平台上运行时涵盖了类似的主题。最近的更改是在 Python 3.3 中进行的允许在代码执行位置定义行为。

PEP 397: Python Launcher for Windows

The Python 3.3 Windows installer now includes a py launcher application that can be used to launch Python applications in a version independent fashion.

This launcher is invoked implicitly when double-clicking *.py files. If only a single Python version is installed on the system, that version will be used to run the file. If multiple versions are installed, the most recent version is used by default, but this can be overridden by including a Unix-style “shebang line” in the Python script.

The launcher can also be used explicitly from the command line as the py application. Running py follows the same version selection rules as implicitly launching scripts, but a more specific version can be selected by passing appropriate arguments (such as -3 to request Python 3 when Python 2 is also installed, or -2.6 to specifclly request an earlier Python version when a more recent version is installed).

In addition to the launcher, the Windows installer now includes an option to add the newly installed Python to the system PATH. (Contributed by Brian Curtin in issue 3561.)

简而言之,在您的代码前加上以下几行:

  • #!/usr/bin/env python2 用于 Python 2.x
  • #!/usr/bin/env python3 用于 Python 3.x