Использование библиотеки подпроцесса: ошибка: нераспознанные аргументы - PullRequest
0 голосов
/ 24 июня 2019

Итак, по сути, у меня есть около 15 сценариев, которые могут подключаться к различным сетевым устройствам с использованием библиотеки SSH.Я хочу создать один файл Python верхнего уровня, который может запускать другие сценарии Python, чтобы пользователь мог решить, какие сценарии он хочет запустить.Мне посоветовали использовать библиотеку подпроцесса, и это, кажется, имеет смысл для того, что я хочу сделать.Важно отметить, что мои скрипты на python содержат аргументы командной строки argparse для запуска, например:

python San_cable_test.py -deviceIP 172.1.1.1 -deviceUsername myUsername -devicePassword myPassword

До сих пор я создал файл python верхнего уровня, настроенный на вызов двухСценарии Python для начала, что пользователь может ввести.Тем не менее, когда я запускаю программу и выбираю один из параметров и получаю пользовательские аргументы, я получаю

error: unrecognized arguments:

Я попробовал его двумя разными способами, и я покажу трассировки:

usage: San_cable_test.py [-h] [-deviceIP DEVICEIP]
The name of this script is: San_cable_test.py
                         [-deviceUsername DEVICEUSERNAME]
                         [-devicePassword DEVICEPASSWORD]
San_cable_test.py: error: unrecognized arguments: 172.1.1.1 myUsername myPassword

и


usage: San_cable_test.py [-h] [-deviceIP DEVICEIP]
                         [-deviceUsername DEVICEUSERNAME]
The name of this script is: San_cable_test.py
                         [-devicePassword DEVICEPASSWORD]
San_cable_test.py: error: unrecognized arguments: -deviceIP 172.1.1.1 -deviceUsername myUsername -devicePassword myPassword


Я впервые использую библиотеку подпроцессов, и я не знаю, правильно ли я называю эти сценарии.Проблема в том, что эти сценарии запускаются в командной строке с использованием argparse, так что это проблема.К сожалению, я использую 2.7.16 из-за этой странной компании, и я пытался заставить своих менеджеров узнать, что 2.7 скоро не будет поддерживаться, но это не актуально на данный момент.Вот важная часть моего кода.Я очень ценю помощь!


def runMain():

    scriptName = os.path.basename(__file__)

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

    scriptPurpose = 'This script is the top-level module that can invoke any script the user desires !\n'

    while True:
        optionPrinter()

        user_input = input("Please select an option for which your heart desires...\n")

        switch_result = mySwitch(user_input)

        if switch_result == "our_Switch":
            deviceIP = raw_input("Enter the IP address for the device")
            deviceUsername = raw_input("Enter the username for the device")
            devicePassword = raw_input("Enter the password for the device")

            subprocess.call(['python', 'our_Switch.py', deviceIP, deviceUsername, devicePassword])

        elif switch_result == "San_cable_test":
            deviceIP = raw_input("Enter the IP address for the device")
            deviceUsername = raw_input("Enter the username for the device")
            devicePassword = raw_input("Enter the password for the device")
            subprocess.call(['python', 'San_cable_test.py', deviceIP, deviceUsername, devicePassword])

        else:
            print("Exiting the program now, have a great day !\n")
            sys.exit(-1)

if __name__ == '__main__':

Вот пример использования argparse в одном из скриптов

def runMain():

    scriptName = os.path.basename(__file__)

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

    scriptPurpose = 'This script enables and disables the SAN switches'

    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()

    if args.deviceIP is None:
        print("The device IP parameter is blank\n")
    else:
        deviceIP = args.deviceIP

    if args.deviceUsername is None:
        print("The device userName parameter is blank\n")
    else:
        deviceUsername = args.deviceUsername

    if args.devicePassword is None:
        print("The device password parameter is blank\n")
    else:
        devicePassword = args.devicePassword

    print("**********************\n")
    print (deviceIP + " " + deviceUsername + " " + devicePassword)
    print("**********************\n")

    print("This script allows the user to enable and disable ports on a SAN switch to see how it behaves\n")

    print("Checking to see if the SAN switch is pingable\n")

    test_ping = canPing(deviceIP)

    if test_ping:
        print("The switch is pingable, let's proceed !\n")
    else:
        print("This device is not pingable unfortunately, sorry... : (\n")
        sys.exit(-1)

    sshConnection = connectToSSH(deviceIP, deviceUsername, devicePassword)

    while True:
        optionPrinter()

        user_input = input("Select an option from the menu\n")

        switch_result = mySwitch_function(user_input)

        if switch_result == 'ShowPort':
            portShow(sshConnection)
        elif switch_result == 'SwitchShow':
            switchShow(sshConnection)
        elif switch_result == 'EnablePort':
            enablePort(sshConnection)
        elif switch_result == 'DisablePort':
            disablePort(sshConnection)
        elif switch_result == 'disableEnable':
            disableEnableIteration(sshConnection)
        else:
            print("Program is exiting now, have a great day/night ! \n")
            sys.exit(-1)

1 Ответ

1 голос
/ 24 июня 2019

Вы пропускаете имена опций перед параметрами.

subprocess.call(['python', 'our_Switch.py', '-deviceIP', deviceIP, '-deviceUsername', deviceUsername, '-devicePassword', devicePassword])

Однако, возможно, будет лучше, если вы измените эти другие скрипты на модули Python, которые вы можете просто импортировать и вызывать напрямую как функции,вместо того, чтобы запускать их как подпроцессы.

...