【问题标题】:How would I pass the value of a function parameter to a variable?如何将函数参数的值传递给变量?
【发布时间】:2019-12-15 08:47:39
【问题描述】:

如何将“ip 参数”的值分​​配给变量以便打印该值?

from netmiko import ConnectHandler

device = ConnectHandler(device_type="cisco_ios", ip="192.168.117.2", 
username="ccna", password="cisco")

connected_device = ip

if device.is_alive():
    print (f"IP Address of connected device is: {connected_device}")

device.disconnect()

Traceback(最近一次调用最后一次): 文件“c:/Users/Main/Documents/Visual Studio 代码 项目/Python_Projects/cisco_router_test.py",
第 5 行,在 connected_device = ip NameError: name 'ip' is not defined

【问题讨论】:

    标签: python


    【解决方案1】:

    您必须在 ConnectHandler 之外定义 ip,因为它只是将它作为变量传递而不是分配它:

    ip="192.168.117.2"
    

    您可以要求输入并像这样使用它:

    ipaddr = input("Enter IP: ")
    
    device = ConnectHandler(device_type="cisco_ios", ip=ipaddr, 
    username="ccna", password="cisco")
    
    connected_device = ipaddr
    
    

    【讨论】:

    • @BrandonHarmon 看到我的更新,这就是你要找的东西
    • 是的,没错,这行得通。我在测试阶段考虑得更多,因为我通常在测试程序时调用函数并直接传递参数。不过谢谢。
    【解决方案2】:

    你应该可以在 python 3.8 中使用:=

    device = ConnectHandler(device_type="cisco_ios", ip := "192.168.117.2", 
    username="ccna", password="cisco")
    
    connected_device = ip
    

    【讨论】:

      猜你喜欢
      • 2015-01-05
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多