用于检查 Python 是否安装的 Powershell 脚本 [英] Powershell script to check if Python is installed

查看:52
本文介绍了用于检查 Python 是否安装的 Powershell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Powershell 脚本检查机器上是否安装了 Python.

I'm trying to check if Python is installed on a machine via a Powershell script.

到目前为止,我的想法是运行以下内容:

My idea so far is to run the following:

$p = iex 'python -V'

如果命令正确执行(检查 $p 属性上的 Exitcode),读取输出并提取版本号.

If the command executes correctly (check the Exitcode on $p property), read the output and extract the version number.

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

However, I'm struggling to capture the output when executing the script in Powershell ISE. It's returning the following:

python : Python 2.7.11
At line:1 char:1
+ python -V
+ ~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Python 2.7.11:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

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

Can someone point in the right direction?

干杯,普拉布

推荐答案

看来 python -V 输出版本字符串到 stderr 而不是 stdout.

It seems that python -V outputs the version string to stderr and not stdout.

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

You can use a stream redirector to redirect the error into the standard output:

# 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 版本都会以这种方式运行,您可以将其缩减为:

If you are certain that all the versions of python you have on your systems will behave this way, you can cut it down to:

$version = (&{python -V}).Exception.Message

这篇关于用于检查 Python 是否安装的 Powershell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆