使用Python的argparse库时,在分配错误之前可能会引用局部变量。需要帮助调试

时间:2019-05-23 16:06:27

标签: python debugging ssh reference argparse

我当前收到一条错误,指出:三个变量deviceIP,deviceUsername和devicePassword的“分配前可能会引用本地变量”。这些参数是使用arparse库添加的,我不太了解为什么会收到这些错误。

我假设这些变量值是使用命令行输入的,但是我尝试在命令行中输入它们,但是没有成功,因为我的程序未编译。这是代码:

#usage: ....py [-h] 
#           [-deviceIP DEVICEIP]
#                       [-deviceUsername DEVICEUSERNAME]
#                       [-devicePassword DEVICEPASSWORD]

def Main():
    # Initialize dynamic time stamp and script name
    beginstamp = datetime.datetime.utcnow().replace(microsecond=0)
    beginDisplayedstamp = getStamp()
    scriptName = os.path.basename(__file__)

    print (" scriptName = ", scriptName)
    scriptPurpose = 'Script to reboot swtich.\n'

    parser = argparse.ArgumentParser(description=scriptPurpose, formatter_class=RawTextHelpFormatter)
    parser.add_argument("-deviceIP", help="Target device IP address", type=str)
    parser.add_argument("-deviceUsername", help="Target device username", type=str)
    parser.add_argument("-devicePassword", help="Target device password", type=str)
    args = parser.parse_args()

    #Section to handle the input parameters
    if args.deviceIP is None:
        line = "Fail, The deviceIP parameter is blank.\n"
        print (line)

    else:
        deviceIP = args.deviceIP

    if args.deviceUsername is None:
        line = "Fail, The deviceUsername parameter is blank.\n"
        print (line)
    else:
        deviceUsername = args.deviceUsername

    if args.devicePassword is None:
        line = "Fail, The devicePassword parameter is blank.\n"
        print (line)
    else:
        devicePassword = args.devicePassword

    print ("**********************")
    print (deviceIP, deviceUsername, devicePassword)

    print ("Checking the connectivity of the device\n"

    ret = ping(deviceIP)
    ret = 1
    #print ret

    if ret:
        print ("DeviceIP is pingabale continue")
    else:
        print ("Device IP not accessible, Give valid IP")

    sys.exit(-1)

这是我运行程序时的错误代码,但也许是因为我不确定如何正确输入这些参数而得到的?


C:/......
 scriptName =  Cisco_switch.py
Traceback (most recent call last):
Fail, The deviceIP parameter is blank.

  File "C:/.....", line 280, in <module>
Fail, The deviceUsername parameter is blank.
    Main()

  File "C:/......", line 225, in Main
Fail, The devicePassword parameter is blank.
    print(deviceIP, deviceUsername, devicePassword)

UnboundLocalError: local variable 'deviceIP' referenced before assignment
**********************

Process finished with exit code 1


感谢您的帮助,谢谢!

0 个答案:

没有答案