I made a .cmd file that runs a specific windows program. But I wrote the full script in Python. How do I embed the .cmd or that code in python?
I made a .cmd file that runs a specific windows program. But I wrote the full script in Python. How do I embed the .cmd or that code in python?
To be able to execute external commands you must use one of the possibilities offered by subprocess . The recommended one is run () . I give you an example that I use, taking into account that the output is not captured.
import subprocess
#...
def cmd(commando):
subprocess.run(commando, shell=True)
Example of use:
# Cambiar el título de la ventada de la consola
cmd('TITLE Título de la ventana')
# Ejecutar cmd externo
cmd('myscript.cmd parametro1 parametro2')
When using shell=True
the parameters are passed as text. You can see it in more detail in this article from Chris Griffith .
If you are interested in reviewing what your code returns, you should use CompletedProcess .
def cmd(commando):
resultado = subprocess.run(commando, shell=True)
# Comprobar resultado, si es diferente de 0 lanza una excepción
resultado.check_returncode()
Note: CompletedProcess is only available from Python 3.5