Проблемы с input () и raw_input () для Python 2.7.Введенные пользователем данные не читаются должным образом.Что здесь происходит? - PullRequest
0 голосов
/ 25 июня 2019

Так что в моей компании меня заставляют использовать python 2.7 из-за продукта по причине совместимости, в который я не буду здесь вдаваться.

Поэтому я пишу программу, которая подключается к устройству с использованием SSH(в частности, переключатель), и я могу фактически получить доступ к устройству с помощью SSH, и это устройство может выполнять проверку связи на моей машине.Эта проблема ?Кажется, что raw_input не воспринимает его как строку.Когда я пытаюсь использовать input (), он выдает мне неверную синтаксическую ошибку.

Для сценариев, которые я пишу, я обычно использую arparse, и пользователь вводит IP-адрес, имя пользователя и пароль через терминал, но я хочуэтот скрипт не использовать argparse и использовать input () или raw_input.Все мои SSH-скрипты работают хорошо, кроме этого, единственный, использующий raw_input и input () вместо argparse

def runMain():

    scriptName = os.path.basename(__file__)

    print("The name of this script is: " + scriptName)

    print("**************************************\n")

    print("This script allows you to enable and disable ports on the SNET or SOOBM switches, have fun ! \n")

    print("**************************************\n")

    optionPrinter_switches_top()

    user_input = raw_input("Make your selection") # This does not work if I change to input(), it exits out of the program

    if user_input == 1:
        print("You selected the SNET switch, lets proceed !")

        deviceIP = input("Enter the IP address for this device")  # I tried changing these to raw_input, I get a syntax issue
        deviceUsername = input("Enter the username for this device")
        devicePassword = input("Enter the password for this device")

        confirm_ping = canPing(deviceIP) # This is a boolean function that works correctly in every script but this one.

        if confirm_ping:
            ssh_SNET = connectToSSH_SNET(deviceIP, deviceUsername, devicePassword)
        else:
           print("Sorry, that device is not even ping-able. Figure that issue out and retry the program...")
           sys.exit(-1)

        while True:
            SNET_options()

            user_choice_SNET = input("Please select an option")

            switch_result = SNET_switch_func(user_choice_SNET)

            if switch_result == "displayInterfaceBrief":
                time.sleep(5)
                displayInterfaceBrief_SNET(ssh_SNET)
            elif switch_result == "enablePort":
                time.sleep(5)
                enablePort_SNET(ssh_SNET)
            elif switch_result == "disablePort":
                disablePort_SNET(ssh_SNET)
            elif switch_result == "switchReboot":
                reboot_SNET_switch(ssh_SNET)
            else:
                print("Exiting program now....")
                sys.exit(-1)

Вот соответствующие проблемы:

user_input = raw_input("Make your selection") # This does not work if I change to input(), it exits out of the program
 deviceIP = input("Enter the IP address for this device")  # I tried changing these to raw_input, I get a syntax issue
 deviceUsername = input("Enter the username for this device")
 devicePassword = input("Enter the password for this device")

confirm_ping = canPing(deviceIP) # This is a boolean function that works correctly in every script but this one.

Заключение?Существует проблема с input () / raw_input ().Что здесь происходит и как я могу это исправить?Я не могу использовать Python 3.7, и это действительно расстраивает.Спасибо за помощь

1 Ответ

0 голосов
/ 25 июня 2019

Попробуйте изменить if user_input == 1: на if int(user_input) == 1:, поскольку функция ввода принимает ввод в строковом формате по умолчанию.

И, если вы хотите использовать input() вместо raw_input() для получения информации от пользователей в python 2.x, тогда вы можете попробовать следующий код:

if hasattr(__builtins__, 'raw_input'):
    input=raw_input

user_input = input("Enter a number: ")
...