Python - Run two scripts at once

Asked

Viewed 2,027 times

2

In have a file x.py and the y.py, in another file I have the following code:

import os

os.system('py -3.7 x.py')
os.system('py -3.7 y.py')

But the problem is that the y.py only executes when executing the x.py ends, as I could do for the two to execute at the same time?

1 answer

4


A Python library for running parallel processes is threading.

Basically, it is possible to declare and execute a process like this:

# Define um processo a partir de uma `função_a_ser_executada(arg1, arg2)`
processo = threading.Thread(target= função_a_ser_executada, args=(arg1, arg2, ))

# Inicia o processo
processo.start()

For your case, run scripts, the function to be executed is the inicia_programa(arquivo_nome). It is necessary to declare a process for each file (x.py and the y.py) and then start the processes:

import threading
import os


def inicia_programa(nome_arquivo):
    os.system('py -3.7 {}'.format(nome_arquivo))
    # Ex: os.system('py -3.7 x.py')

if __name__ == "__main__":

    arquivos = ['x.py','y.py']

    processos = []
    for arquivo in arquivos:
        processos.append(threading.Thread(target=inicia_programa, args=(arquivo,)))
        # Ex: adicionar o porcesso `threading.Thread(target=inicia_programa, args=('x.py',))`

    for processo in processos:
        processo.start()
  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.