运行 python-脚本作为终端程序(没有 .py-file-ending)来自 Windows Server 2016 的任何地方

Run python-script as terminal program (without .py-file-ending) from anywhere on Windows Server 2016

在 Windows Server 2012R2 上,我将如何从终端在任何目录中制作一个特定的 python-脚本 (D:/App/applic.py) 可执行文件,而不会引起任何 python 也不是 .py 文件结尾?在此服务器上,我希望所有用户都能够键入:

applic 2017 -v

在终端的任何地方唤起

python D:/Applic_dev/applic.py 2017 -v

我不是在寻找类似 py2exe 的解决方案,因为 Python 3 将始终 服务器上。

PS。我的 python-脚本使用 plac 来解析命令行参数。

在受保护的位置(用户无法编辑的位置)创建一个 cmd 文件

applic.cmd

@ECHO OFF
REM This will be wherever the python executable is
SET "PY=%PROGRAMFILES%\Pythonx.x\python.exe"

REM This checks to see if the script is called without arguments
IF [%*] EQU [] (
    @CALL %PY% "D:/App/applic.py"
    EXIT /B
)
REM %* contains all arguments the script received
@CALL %PY% "D:/App/applic.py" %*
EXIT /B

在这里,编辑您的 PATH 环境变量以包含此受保护位置所在的路径。

Automated PowerShell way

$ProtectedFolderLocation = 'C:\Windows\System32\Applic'
$RegKey = 'HKLM:\System\CurrentControlSet\Control\Session Manager\Environment'

$Path = (Get-ItemProperty -Path $RegKey).Path
If ($Path[-1] -ne ';') { $Path += ";$ProtectedFolderLocation;" }
Else { $Path += "$ProtectedFolderLocation;" }

Set-ItemProperty -Path $RegKey -Name 'PATH' -Value $Path

现在,当用户从 cmd.exe 调用 applic 时,他们将调用上面指定的脚本。