user282190
user282190

Reputation: 270

Python answering command prompts in terminal

I needed to some help on developing a piece of python software. Basically when it tries to do:

os.system("commandHere usernameHere")

I need it to answer the password prompt that comes up asking for the password. The password cannot be added in as the third argument unfortunately and I have no idea how to handle this. Also, another question, how do I receive the output from terminal into my python program?

Thank you! :)

Upvotes: 1

Views: 2605

Answers (1)

Aaron Christiansen
Aaron Christiansen

Reputation: 11837

You're better using subprocess.Popen than os.system, as it allows you to send data to and read data from the process. Note that Popen takes a list of commands and arguments rather than a string with spaces, so ["commandHere", "usernameHere"] rather than "commandHere usernameHere". Once the Popen is complete, we can write into the process and read output from it as shown below.

import subprocess

p = subprocess.Popen(["commandHere", "usernameHere"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write(b"yourPassword\n")   # What you need to input
result = p.stdout.read()           # The program's output
print(result)

Upvotes: 2

Related Questions