簡體   English   中英

一起運行和監控多個 shell 命令的優雅方式是什么?

[英]What is the elegant way of running and monitoring multiple shell commands together?

這是我正在做的一個例子; this shell snippet runs a django web server as well as an npm process that runs webpack (both monitor for file changes and reload/recompile, etc). 為了方便起見,我將它們組合成一個命令,我可以通過 npm 運行,但我覺得我忘記了一些看起來比這更好的簡單命令:

p=0; q=0; endit() { kill -9 $p; kill -9 $q; }; trap endit INT; records/manage.py runserver & p=$!; npm run watch & wait; q=$!; wait $p; wait $q; endit

幫助我和我老化的 memory ::)

您可以通過使用kill $(jobs -p)終止所有正在運行的作業來擺脫pq變量。 同樣,沒有 arguments 的wait將等到所有正在運行的作業完成。

關於您的代碼的另外 2 個注釋:

  • 您應該在 trap 命令中調用exit ,否則您的腳本即使在收到SIGINT后仍將繼續(導致最終wait調用失敗,因為進程已經終止)。
  • 您不應該在腳本末尾調用陷阱命令( endit() ),因為此時進程由於wait調用而已經完成。

我使用演示性sleep命令測試了代碼:

trap 'kill $(jobs -p); exit' INT;
sleep 5 &
sleep 5 &
wait

這是我想的最簡單的版本,我猜。 在我的情況下,用法是:

runon.py 'records/manage.py runserver' 'npm run watch'

這行得通,只是感覺還有更簡單的東西。

#!/usr/bin/env python3

import sys
import argparse
import subprocess
import time
import shlex

parser = argparse.ArgumentParser(
    description='Manage multiple running commands.')
parser.add_argument('cmds', metavar="'cmdline -opts'", type=str, nargs='+',
                    help='a shell command to run')
args = parser.parse_args()

calls = {}.fromkeys(args.cmds)
for cmd in calls.keys():
    calls[cmd] = subprocess.Popen(shlex.split(cmd), text=True)
    print'start(%d): %s' % (calls[cmd].pid, cmd)

while calls:
    finished = []
    for name, call in calls.items():
        ret = call.poll()
        if ret is not None:
            print('return(%d): %s' % (ret, name))
            finished.append(name)
    for n in finished:
        calls.pop(n)
    time.sleep(0.5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM