Home >Backend Development >Python Tutorial >Automations with Python.

Automations with Python.

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 15:15:16318browse

Automações com Python.

This code is designed to run Python programs on separate terminals asynchronously. I will explain step by step what each part of the code does.

1. Subprocess Module Import

import subprocess

The subprocess module allows you to create and manage operating system processes from a Python program. It is used here to launch Python programs in new terminal windows.

2. execute_program function

def executar_programa(caminho_programa):
    try:
        # Executa o programa em uma nova janela de terminal
        subprocess.Popen(
            ["python", caminho_programa],
            creationflags=subprocess.CREATE_NEW_CONSOLE
        )
        print(f"Programa {caminho_programa} iniciado com sucesso.")
    except Exception as e:
        print(f"Erro ao iniciar o programa {caminho_programa}: {e}")

This function is responsible for running a Python program in a new terminal window:

  • Program_path argument: The absolute path of the Python script you want to run.

  • subprocess.Popen: Starts a new process in the operating system.

    • The list ["python", program_path] is the command that will be executed in the terminal. The first "python" item is the Python interpreter and the second program_path item is the Python script to be executed.
    • creationflags=subprocess.CREATE_NEW_CONSOLE: This flag creates a new terminal window for the process instead of running it in the current terminal window.
  • try and except: The try block attempts to execute the program. If an error occurs (such as an incorrect script path), the except block catches the exception and prints an error message.

3. main function

def main():
    # Caminhos para os programas que você deseja executar
    programa1 = r"C:\Users\hbvbr\Documents\DEV\AlgotradingCopia\eaEquiti\eaEquiti108.py"
    programa2 = r"C:\Users\hbvbr\Documents\DEV\AlgotradingCopia\eaEquiti690\eaEquiti690.py"
    programa3 = r"C:\Users\hbvbr\Documents\DEV\AlgotradingCopia\eaFtmo\eaFtmo.py"
    programa4 = r"C:\Users\hbvbr\Documents\DEV\AlgotradingCopia\eaEquiti224\eaEquiti224.py"

    # Executa cada programa em um terminal separado
    executar_programa(programa1)
    executar_programa(programa2)
    executar_programa(programa3)
    executar_programa(programa4)

In the main function:

  • Defining paths for programs: Here, four variables are defined (program1, program2, program3, program4) with the absolute paths of the Python scripts you want to run. Paths are written as raw strings (prefixed with r) to avoid backslash issues.

  • Call to the execute_program function: For each program, the execute_program function is called. Each Python script runs in a new terminal window.

4. Conditional Execution if __name__ == "__main__":

import subprocess
  • if __name__ == "__main__":: This condition checks whether the Python file is being executed directly (and not imported as a module in another script). If executed directly, the main() function will be called and programs will start.

Flow Summary:

  1. The script starts by executing the main function.
  2. The main function calls execute_programa for each of the four scripts, passing the program paths.
  3. The execute_program function runs each Python script in a new terminal window, using subprocess.Popen.
  4. If there is any error while trying to run any program, the error will be captured and a message will be displayed.

How it works in the operating system:

  • The subprocess.Popen with CREATE_NEW_CONSOLE will open a new operating system terminal window (on Windows, usually cmd or PowerShell) and run the specified Python program in each of these windows.

This is the basic functioning of the code! If you need more details or adjustments, feel free to ask.

The above is the detailed content of Automations with Python.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn