![](/img/trans.png)
[英]What is the difference of running commands in terminal and shell script?
[英]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)
終止所有正在運行的作業來擺脫p
和q
變量。 同樣,沒有 arguments 的wait
將等到所有正在運行的作業完成。
關於您的代碼的另外 2 個注釋:
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.