Python subprocess: interacting with a shell script

♀尐吖头ヾ 提交于 2019-12-22 09:37:03

问题


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 yenter.

e.g.,

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?


回答1:


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


来源:https://stackoverflow.com/questions/9555477/python-subprocess-interacting-with-a-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!