python-3.x - 如何将 Azure-cli 命令的输出保存在变量中

标签 python-3.x azure azure-cli

在 python 3.5 中使用 azure-cli 并从脚本调用命令时,我无法控制控制台中的输出。

当执行命令时,它会将结果打印到控制台,但我正在努力获取结果并将其放入变量中进行分析。

from azure.cli.core import get_default_cli

class AzureCmd():
        def __init__(self, username, password):
            self.username = username
            self.password = password

        def login(self, tenant):
            login_successfull = get_default_cli().invoke(['login',
                                                          '--tenant', tenant,
                                                          '--username', self.username,
                                                          '--password', self.password]) == 0
            return login_successfull

        def list_vm(self, tenant):
            list_vm = get_default_cli().invoke(['vm', 'list', '--output', 'json'])
            print(list_vm)


    tenant = 'mytenant.onmicrosoft.com'
    cmd = AzureCmd('login', 'mypassword')
    cmd.login(tenant)
    cmd.list_vm(tenant)

这是我的脚本尝试。

我想要实现的目标:执行 cmd.login(tenant) 时没有得到任何输出。 我不想在变量 login_successfull 和 list_vm 中获取 0(成功)或 1(失败),而是想将 get_default_cli().invoke() 的输出保存在其中。

最佳答案

我遇到了同样的问题,并找到了解决方案,我还发现很多人提供了在大多数情况下正常工作的标准解决方案,但他们没有验证它是否适用于这种情况,结果是 az cli是一种边缘情况。
我认为这个问题与 az cli 基于 python 有关。

Win10CommandPrompt:\> 其中 az C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd

如果您查看该文件,您会看到类似这样的内容,并发现 Azure CLI 只是 python:

python.exe -IBm azure.cli

所以要做你想做的事,试试这个(它对我有用):

import subprocess
out = subprocess.run(['python', '-IBm', 'azure.cli', '-h'], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(out) 
#this is equivalent to "az -h'

除非每个参数都是逗号分隔的字符串列表,否则上述语法将不起作用,在阅读如何使用 python popen 执行多个参数后,我发现了一种我更喜欢的语法:

import subprocess
azcmd = "az ad sp create-for-rbac --name " + SPName + " --scopes /subscriptions/" + subscriptionid
out = subprocess.run(azcmd, shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')
print(out)

关于python-3.x - 如何将 Azure-cli 命令的输出保存在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52340497/

相关文章:

python - 在 Turtle 中不设置动画 - Python 3.4?

python - 理解 python id() 的唯一性

javascript - Azure:无法在exports.post调用未定义的方法 'then'

python - Azure Function - 触发包含 Azure CLI 命令的 Python 脚本

azure - az 登录错误 : Please ensure you have network connection. 错误详细信息 : HTTPSConnectionPool(host ='login.microsoftonline.com' , 端口=443)

json - python 3 : deserialize nested dictionaries from sqlite

python - MySQL 'SHOW TABLES' 返回计数而不是列表 (Python)

azure - 以编程方式动态生成 Azure Function 的访问代码

c# - 是否有 PBix 文件格式的文档/API?

azure - 使用 Azure CLI 将 Azure 标记参数传递到 Bicep 模板