на локальную переменную можно ссылаться до ошибки присваивания при использовании библиотеки Python argparse.Нужна помощь в отладке - PullRequest
0 голосов
/ 23 мая 2019

В настоящее время я получаю сообщение об ошибке: «на локальную переменную можно ссылаться перед назначением» для трех переменных: 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


Я ценю помощь, спасибо!

...