Python 同时执行多个.py文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18216205/
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
Execute multiple .py files at the same time
提问by Petesta
I have three .py files that I want to run at the same time in a Python script file. I initially called subprocess.call()
three times (once for each .py file) but remembered that it blocks until the command is finished. I tried subprocess.Popen(['screen', 'python_file'])
since I believe it doesn't block but when I was checking for the processes with screen -ls
there was only one process running. How do I get all three programs running at the same time with a Python script? Should I be using the multiprocessing
or multithreading
library?
我想在 Python 脚本文件中同时运行三个 .py 文件。我最初调用了subprocess.call()
3 次(每个 .py 文件调用一次),但记得它会阻塞直到命令完成。我尝试过,subprocess.Popen(['screen', 'python_file'])
因为我相信它不会阻塞,但是当我检查进程时screen -ls
,只有一个进程正在运行。如何使用 Python 脚本同时运行所有三个程序?我应该使用multiprocessing
还是multithreading
库?
Edit: The other processes aren't supposed to finish since they're running in an infinite loop. Here's exactly what I had in my Python script file. I'm using screen
because each .py file has stdout logged onto the terminal and I want to be able to see what is being logged for each one.
编辑:其他进程不应该完成,因为它们在无限循环中运行。这正是我在 Python 脚本文件中的内容。我正在使用screen
是因为每个 .py 文件都有标准输出登录到终端,我希望能够看到每个文件记录的内容。
subprocess.Popen(['screen', './submitter.py'])
subprocess.Popen(['screen', './worker.py'])
subprocess.Popen(['screen', './tester.py'])
subprocess.Popen(['screen', './submitter.py'])
subprocess.Popen(['screen', './worker.py'])
subprocess.Popen(['screen', './tester.py'])
采纳答案by xlharambe
If you want to use multiprocessing
, you can try this:
如果你想使用multiprocessing
,你可以试试这个:
import multiprocessing
def worker(file):
# your subprocess code
if __name__ == '__main__':
files = ["path/to/file1.py","path/to/file2.py","path/to/file3.py"]
for i in files:
p = multiprocessing.Process(target=worker, args=(i,))
p.start()