python - "if"基于命令的语句?

标签 python python-3.x if-statement

我从Python的文档中了解到,我可以使用以下格式检查条件:

if x < 0:
else:
    print('Else code')

我想运行命令并检查该命令是否成功,但收到“SyntaxError:无效语法”错误。救命!

我的格式大致是:

if myCommand(parameters):
    print("It worked")
else:
    print("It failed")
    if mySecondCommand(parameters):
        print("2nd command worked")
    else:
        print("2nd command failed")

这是我使用 Netmiko 库的实际代码:

from netmiko import ConnectHandler
if net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='domain.login', password='DomainPassword'):
    print("Domain login succeeded.")
else:
    print("Domain login failed.")
    if net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='StandardUsername', password='StandardPassword'):
        print("Standard login worked")
    else:
        print("Standard login failed")

我得到的输出是:

if net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.444', username='domain.login', password='DomainPassword'):
               ^
SyntaxError: invalid syntax

最佳答案

考虑到对此问题提供的评论,似乎您本质上需要的是如何知道连接是否失败。由于连接失败会引发异常,因此 if 语句不足以/不需要实现您想要的效果。相反,您想这样做:

from netmiko import ConnectHandler
try:
    net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44', username='domain.login', password='DomainPassword')
    print("Domain login succeeded.")
except:
    print("Domain login failed.")

    try:
        net_connect = ConnectHandler(device_type='cisco_ios', ip='11.22.33.44',username='StandardUsername', password='StandardPassword')
        print("Standard login worked")
    except:
        print("Standard login failed")

如果您在 Python 中没有遇到过“try- except”语句,我建议您查找一下。

关于python - "if"基于命令的语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48695499/

相关文章:

python - python中的极端浮点精度数1.0-(0.1^200)

python-3.x - pandas DatetimeIndex 到 matplotlib x-ticks

python - 通过Python中的唯一值计算数组组的平均值

java - 为什么这不起作用? java

Javascript 循环 if 语句进行文本冒险

python - 从选定位置导入 Python 模块

python - 如何在 Pandas 中保存符合特定条件的先前结果

python - ipython CheckboxWidget 放置

python - 为什么此代码会导致 Excel 中出现按字母顺序排列的列列表?

excel - 如果 1 列或两列都有单词,则输入文本