简体   繁体   中英

Providing input to command in sub process in python

I want to automate command-line utility that requires inputs at prompt. I have written the below program, but it is not working. Please help.

def execute_command_login(command,password,inputParameter=''):
    try:
        command = str(command).split(" ")
        p = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin =subprocess.PIPE,bufsize=0)
#         p.stdin.write(password)
        time.sleep(2)
        if(p.stdout):
            p.stdin.write(str(password))
            if(p.stdout):
                p.stdin.write(str(inputParameter))
        out,err = p.communicate(password)
        out = str(out).split("\n")
        out.remove('')
        if(err):
            return err
        else:
            return out
    except:
        print("Error while executing command"+str(sys.exc_info()[1]))

The Pexcept module will do what you want: https://pexpect.readthedocs.io/en/stable/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM