简体   繁体   English

同时运行多个Python脚本然后按顺序运行

[英]Running multiple Python scripts simultaneously and then sequentially

I can run multiple Python scripts simultaneously from a bash script like this; 我可以从这样的bash脚本同时运行多个Python脚本;

#!/bin/bash
python pr1.py & 
python pr2.py &
python aop.py &
python loader.py &

But what if I want a batch to fire simultaneously and after they've run, start some more sequentially. 但是如果我想要一个批次同时开火并且在它们运行之后,又开始更顺序地开始。 Will this work?: 这有用吗?:

#!/bin/bash
python pr1.py & 
python pr2.py &
python ap.py &
python loader.py
python cain.py
python able.py

Once you put & at the end, it runs as a background process. 一旦你把它放在最后,它就作为后台进程运行。 Hence all the scripts ending with & run in parallel. 因此所有脚本以&结尾并行运行。

To run the other 3 scripts in sequential order you can try both: 要按顺序运行其他3个脚本,您可以尝试两个:

&& runs the next script only if the preceding script has run successfully &&仅在前面的脚本成功运行时才运行下一个脚本

python loader.py && python cain.py && python able.py 

|| runs scripts sequentially irrespective of the result of preceding script 无论先前脚本的结果如何,都按顺序运行脚本

python loader.py || python cain.py || python able.py

On your bash script you can simply add the wait command like this: 在bash脚本中,您只需添加wait命令,如下所示:

#!/bin/bash
python pr1.py & 
python pr2.py &
python ap.py &
wait
python loader.py
python cain.py
python able.py

wait will, obviously, wait for all the jobs (the background proccess you fired) to be finished for it to continue. 显然, wait将等待所有工作(你解雇的后台进程)才能继续。

With the & command you are running the scripts in the background. 使用&命令,您将在后台运行脚本。 you could add a check in a loop to run the command jobs and see if it continues to return a list of jobs. 您可以在循环中添加一个检查以运行命令作业,并查看它是否继续返回作业列表。 when it stops you can continue with your next batch of python calls. 当它停止时,你可以继续下一批python调用。

Why not try it out ? 为什么不尝试一下呢?

#1.py
import time
time.sleep(3)
print("First script")

#2.py
import time
time.sleep(3)
print("Second script")

If you put the processes into background, you will see the output from both the python scripts at the same time. 如果将进程置于后台,您将同时看到两个python脚本的输出。

#!/bin/bash
python 1.py &
python 2.py &

If you execute it without the & , then you will see the output from the second script after 6 seconds. 如果在没有&情况下执行它,那么您将在6秒后看到第二个脚本的输出。

#!/bin/bash
python 1.py
python 2.py

PS: Be careful to take care of dependencies and concurrent access issues while running it in parallel PS:在并行运行时要小心处理依赖项和并发访问问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM