multiple commands with python subprocess

1

I'm developing a system (college work) that consists of a website for the use of a particular board. The problem is that to run the code on the card, I need to execute a lot of commands.

Currently my code looks like this:

def run():
    comando = "cd nke/NKE0.7e/Placa && make clean && make && sudo make ispu && cd .. && sudo ./terminal64"
    print(comando)
    # print(os.system(comando)
    process = subprocess.Popen(comando, stdout=subprocess.PIPE)
    out, err = process.communicate()
    print(out)

The problem is that terminal64 never ends (this is not a bug), so I would need to set a time for it to run and kill it. After that (for example, 2 minutes), I searched and I understood this can be done using the subprocess library, but I could not execute the same command that was running in os.system in it. Can anyone help me to implement this command in subprocess or to set a timeout in terminal64 ?

    
asked by anonymous 04.07.2018 / 20:46

1 answer

1

The method Popen.communicate () has a parameter, called timeout which does exactly what you need, waits for n seconds, and in case the process has not returned, it kills it and triggers a TimeoutExpired exception. The code looks like this:

def run():
    comando = "cd nke/NKE0.7e/Placa && make clean && make && sudo make ispu && cd .. && sudo ./terminal64"

    process = subprocess.Popen(comando, stdout=subprocess.PIPE)
    # espera por 2 minutos
    out, err = process.communicate(timeout=120) 
    print(out)
    
11.07.2018 / 04:26