Home >Backend Development >Python Tutorial >Automations with 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.
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.
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.
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.
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.
import subprocess
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!