简体   繁体   中英

Python subprocess: interacting with a shell script

I have a shell script which asks the user for too many questions.

I want to answer every question that ends with : with a enter , and every question that ends with a ? with y enter .

eg,

Enter your name:
enter

Enter your email:
enter

...

Are you sure these details are correct?
yenter

I have started the subprocess with:

subprocess.Popen(shell=True, stdout=sp.PIPE, stderr=sp.STDOUT, stdin=sp.PIPE)

How do I poll over the script's output, waiting for the question to appear?

Try something like this (I have not tested it):

import pexpect

child = pexpect.spawn('yourprogram')
while True:
  found = child.expect ([r':$', r'\?$', pexpect.EOF])
  if found == 0:
    child.send('\n')
  elif found == 1:
    child.send('y\n')
  else:  # EOF
     return

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