I want to run a command which prompts me to enter yes/no or y/n or whatever. If I just run the command local("my_command")
then it stops and asks me for input. When I type what is needed, script continues to work. How can I automatically respond to the prompt?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Starting from version
1.9
, Fabric includes a way of managing this properly.The section about Prompts in the Fabric documentation says:
You should be able to make Fabric automatically answer prompts like this:
Putting this as an answer though its a comment from @BobNadler
run("yes | my_command");
Note: this answer is several years old, and in the mean time fabric has (interestingly similar looking) implementation of this. See the answer by @timothée-jeannin below.
See https://stackoverflow.com/a/10007635/708221
pip install fexpect
Fexpect adds answering to prompts to fabric with use of pexpect
To expand a bit on Timothée's excellent answer, here's the code that Fabric uses when checking the
prompts
dictionary.Fabric uses
.endswith
for its check, so make sure you include trailing spaces in the string you use as a key in theprompts
dictionary.For example - let's say you are trying to automate the Django test database prompt
All we need is enough of the end of the prompt so that it is unique. Include trailing spaces.
I have used simple echo pipes to answer prompts with Fabric.
In Fabric 2.1, this can be accomplished using the auto-respond example that is available through the invoke package (a dependency of Fabric 2.1):
Note that this is not limited to sudo passwords and can be used anywhere where you have a pattern to match for and a canned response (that may not be a password).
There are a couple of tips:
pty=True
is probably always necessarypattern
specified within theResponder
can often include spaces at the end of the line so try adding spaces when thewatcher
doesn't seem to match.According to the note discussed at the end of the watcher docs:
The pattern argument to Responder is treated as a regular expression, requiring more care (note how we had to escape our square-brackets in the above example) but providing more power as well.
So, don't forget to escape (using backslashes) where necessary.