同时运行多个 Python 脚本,然后依次运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42072715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running multiple Python scripts simultaneously and then sequentially
提问by manners
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
回答by v.coder
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
回答by Carlos Afonso
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
显然,将等待所有作业(您解雇的后台进程)完成以继续。
回答by LhasaDad
With the & command you are running the scripts in the background. you could add a check in a loop to run the command jobsand see if it continues to return a list of jobs. when it stops you can continue with your next batch of python calls.
使用 & 命令,您可以在后台运行脚本。您可以在循环中添加检查以运行命令作业并查看它是否继续返回作业列表。当它停止时,您可以继续进行下一批 python 调用。
回答by pmuntima
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:并行运行时注意处理依赖和并发访问问题