本文介绍了Python子进程:与shell脚本交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个shell脚本,询问用户太多问题。

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

我想用回答每个以结尾的问题:,并且每个以结尾的问题? y

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

例如,


Enter your name:


Enter your email:


...

Are you sure these details are correct?

我已启动子流程:

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

这篇关于Python子进程:与shell脚本交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:34