OpenStove
OpenStove

Reputation: 734

pass answers to popen.subprocess

Is there a way to easily pass answers to a executable in python ?

I have a shell install script (third party), it is asking for some parameter before doing install. I'd like to provide that parameter from my python script.

Is something possible ? like subprocess.popen(myscript,["answer1","answer2"])

Upvotes: 1

Views: 199

Answers (2)

jfs
jfs

Reputation: 414207

Is something possible ? like subprocess.popen(myscript,["answer1","answer2"])

Yes. If you know all the answers then you could use Popen.communicate() to pass the answers:

#!/usr/bin/env python
from subprocess import Popen, PIPE

process = Popen(myscript, stdin=PIPE, universal_newlines=True)
process.communicate("\n".join(["answer1", "answer2"]))

It may fail in some cases and you could use pexpect module (as @Robin Davis suggested), to workaround possible block-buffering issues or issues when input/output is outside of standard streams. See Q: Why not just use a pipe (popen())?

Upvotes: 1

Robin Davis
Robin Davis

Reputation: 632

There is a great Python module that does exactly this, called pexpect

Here's an example of using it to run scp interactively (from the pexpect docs):

child = pexpect.spawn('scp foo [email protected]:.')
child.expect ('Password:') # wait for 'Password:' to show up
child.sendline (mypassword)

Upvotes: 1

Related Questions