简体   繁体   English

同时运行多个python脚本而无需创建多个脚本

[英]concurrently run multiple python scripts without creating multiple scripts

I hope i can explain this well.. (english is not my first language) but in this question they ask to run multiple python scripts simultaneously. 我希望我能很好地解释这一点..(英语不是我的第一语言),但是在这个问题上,他们要求同时运行多个python脚本。 this is exactly how im doing it right now, basically just excecuting my multiple scripts with & in bash 正是我现在的操作方式,基本上只是使用bash中的&执行我的多个脚本

what im trying to do is avoid creating multiple scripts and would like a script that can run all of them simultaneously 我想做的是避免创建多个脚本,而是想要一个可以同时运行所有脚本的脚本

on of the scripts looks like this (similar to all my other scripts) 其中一个脚本看起来像这样(类似于我所有其他脚本)

while True:
    text = "some shell script"
    os.system(text)

I finding it difficult to use a while loop, or any kind of loop because it executes them one after the other and it got really slow. 我发现很难使用while循环或任何形式的循环,因为它一个接一个地执行它们,而且速度非常慢。 I'm very unfamiliar with python and not so good at programming.. so any help would be great 我对python非常不熟悉,并且不太擅长编程..所以任何帮助都将是很棒的

You could use os.fork() to spawn in a new process for each script. 您可以使用os.fork()在每个脚本的新进程中生成。 ie

text = "some shell script"
pid = os.fork()
if pid == 0
    os.system(text)
    sys.exit()

This will make a new process and execute the script in it, then exit upon completion. 这将创建一个新进程并在其中执行脚本,然后在完成后退出。 Although doing so in a while loop would just keep creating new processes up until the os stops it. 尽管在while循环中这样做只会继续创建新进程,直到os停止它为止。

If you have a list of programs you want to execute it would be better to iterate over them with a for loop. 如果您有要执行的程序列表,最好使用for循环遍历它们。 eg 例如

programs = ['test1.py', 'test2.py', 'test3.py']
for program in programs:
    pid = os.fork()
    if pid == 0
        os.system(program)
        sys.exit()

I would also advice using subprocess.call() over os.system() as it was written to replace it. 我也建议使用os.system ()上的subprocess.call()来代替它。 It allows you to easily handle the input and output of the program being executed. 它使您可以轻松处理正在执行的程序的输入和输出。

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

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