检查是否安装了Python的Powershell脚本

2024-10-01 09:34:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过Powershell脚本检查Python是否安装在机器上。在

到目前为止,我的想法是:

$p = iex 'python -V'

如果命令执行正确(检查Exitcodeon $p属性),则读取输出并提取版本号。在

但是,在Powershell ISE中执行脚本时,我很难捕获输出。它返回以下内容:

^{pr2}$

有人能指出正确的方向吗?在

干杯, 普拉布


Tags: 命令脚本机器属性版本号方向iexpowershell
1条回答
网友
1楼 · 发布于 2024-10-01 09:34:47

似乎python -V将版本字符串输出到stderr,而不是{}。在

您可以使用流重定向器将错误重定向到标准输出:

# redirect stderr into stdout
$p = &{python -V} 2>&1
# check if an ErrorRecord was returned
$version = if($p -is [System.Management.Automation.ErrorRecord])
{
    # grab the version string from the error message
    $p.Exception.Message
}
else 
{
    # otherwise return as is
    $p
}

如果您确定系统上的所有python版本都会这样做,可以将其缩减为:

^{pr2}$

相关问题 更多 >