简体   繁体   中英

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. this is exactly how im doing it right now, basically just excecuting my multiple scripts with & in 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. I'm very unfamiliar with python and not so good at programming.. so any help would be great

You could use os.fork() to spawn in a new process for each script. 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.

If you have a list of programs you want to execute it would be better to iterate over them with a for loop. 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. It allows you to easily handle the input and output of the program being executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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