获取shell脚本以等待来自python程序的特定响应

oyxsuwqo  于 2022-11-16  发布在  Shell
关注(0)|答案(1)|浏览(155)

我正在尝试编写一个脚本,它调用一个python程序,暂停直到程序输出某个消息(而不是程序结束时),然后继续前进。
如果我有一个这样的example.py,它无限期地运行:

doSomething()
print('I did something')
doSomethingElseForever()

我想要一个这样的脚本:

echo "Running python program"
python3 example.py &
waitForOutput("I did something")
echo "Python program did something, it's still running in the background"
doSomeMoreScriptStuff

理想情况下,我只需要运行脚本,它就会启动example.py,暂停直到example.py输出“I did something”,然后继续启动更多的程序或其他程序,而不会停止example.py(因此会出现&)。
顺便说一句,我在Ubuntu工作。
编辑:我认为在我的特定应用程序中,我可以修改我的python脚本来创建一个文件,而不是print(),但是为了学习(因为这似乎是一种复杂的操作方式),让我们假设我不能编辑python文件,所以我所要处理的就是print()语句的已知输出。

x7yiwoj4

x7yiwoj41#

你可以用pexpect来实现这一点。我启动一个线程,它调用pexpect.spawn()来运行你的子脚本。它等待你想要的输出,然后设置一个事件,这样主程序就知道事件已经发生了。然后它等待子脚本退出,这反过来又允许主程序退出:

#!/usr/bin/env python3

import pexpect
import time
import threading

doneIt = threading.Event()

def childHandler():
   """Spawns the child and manages its output"""
  
   global doneIt 
   print('HANDLER: Spawning child')
   child = pexpect.spawn('./example.sh')
   print('HANDLER: Child spawned, waiting for it to do something')
   child.expect('I did something')
   doneIt.set()
   print('HANDLER: Waiting for child to finish')
   child.expect(pexpect.EOF)
   print('HANDLER: Done')

if __name__ == "__main__":
   print('MAIN: Starting')
   cH = threading.Thread(target=childHandler)
   cH.start()

   # Wait for event and do other stuff, like printing
   while True:
      print('MAIN: waiting for child to do something')
      if doneIt.wait(1):
          break

   print('MAIN: Continuing...')

   # Wait till childHandler exits before exiting
   cH.join() 
   print('MAIN: Exit')

我使用这个example.sh作为Python脚本的模型,您可以调用它:

#!/bin/bash

LOG="run.txt"
date +'Running: %H:%M:%S' > "$LOG"
for ((i=8;i>0;i--)) ; do
  date +'Running: %H:%M:%S' >> "$LOG"
  sleep 1
done

date +'SUCCESS: %H:%M:%S' >> "$LOG"
echo "I did something"

for ((i=1;i<10;i++)) ; do
  date +'Continuing: %H:%M:%S' >> "$LOG"
  sleep 1
done

date +'DONE: %H:%M:%S' >> "$LOG"

日志如下:

Running: 13:05:27
Running: 13:05:27
Running: 13:05:28
Running: 13:05:29
Running: 13:05:30
Running: 13:05:31
Running: 13:05:32
Running: 13:05:33
Running: 13:05:34
SUCCESS: 13:05:35
Continuing: 13:05:35
Continuing: 13:05:36
Continuing: 13:05:37
Continuing: 13:05:38
Continuing: 13:05:39
Continuing: 13:05:40
Continuing: 13:05:41
Continuing: 13:05:42
Continuing: 13:05:43
DONE: 13:05:44

相关问题