multiple commands with python subprocess

Asked

Viewed 1,547 times

1

I am developing a system (college work) that consists of a website for the use of a certain board. The problem is that to run the code on the board, I need to run a bunch of commands.

Currently my code is 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 the terminal64 never ends (this is not a mistake), so I would need to set a time for it to run and kill it. After that (example, 2 minutes), I searched and from what I understand it can be done using the library subprocess, but I was unable to execute the same command I was running on os.system in it.

Can someone help me implement this command in the subprocess or to set a timeout in the terminal64?

  • What is the output you expect to get in print(out), since the command never ends? I’ve already given a suggested implementation of timeout here on the site if you want to study it.

  • Hello @Andersoncarloswoss the terminal command monitors the code that will run on the board and gives me a series of information of the same, but after the code reaches the end the board goes into standby mode and printa information dispensable eternally,as soon as I get home I’ll study your code and thank you

1 answer

1

The method Popen.communicate() has a parameter, called timeout that does exactly what you need, waits for n seconds and, if the process has not returned, kills it and triggers a Timeoutexpired exception. The code would look 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)

Browser other questions tagged

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