Python Forum
pass arguments from bat file to pyhon script from application
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pass arguments from bat file to pyhon script from application
#1
Hi

I have an application that allows me execute a bat file. I can't execute a python file.

I need to pass the arguments of the application to python script. So I do:

echo "%*" > c:\script\salida.txt
python c:\script\envio.py %*
In python I execute a simple python program to store arguments in a file, but I see don't works. If I execute in terminal works but with the application doesn't works. The argumentos file doesn't store the arguments.

import sys
import os

def main():

if len(sys.argv) < 2:

print("Por favor, proporciona argumentos al script.")

return

argumentos = sys.argv[1:]
ruta_directorio = r"C:\script"

nombre_archivo = "argumentos.txt"
ruta_completa = os.path.join(ruta_directorio, nombre_archivo)

try:

os.makedirs(ruta_directorio, exist_ok=True)
with open(ruta_completa, "w") as archivo:

for argumento in argumentos:

archivo.write(argumento + "\n")

print(f"Argumentos guardados en '{ruta_completa}'")

except Exception as e:

print(f"Error al escribir en el archivo: {e}")

if __name__ == "__main__":

main()
Any help? Thanks
Reply
#2
(Jan-12-2025, 10:53 PM)absolut Wrote: Hi

I have an application that allows me execute a bat file. I can't execute a python file.

I need to pass the arguments of the application to python script. So I do:

echo "%*" > c:\script\salida.txt
python c:\script\envio.py %*
In python I execute a simple python program to store arguments in a file, but I see don't works. If I execute in terminal works but with the application doesn't works. The argumentos file doesn't store the arguments.

import sys
import os

def main():

if len(sys.argv) < 2:

print("Por favor, proporciona argumentos al script.")

return

argumentos = sys.argv[1:]
ruta_directorio = r"C:\script"

nombre_archivo = "argumentos.txt"
ruta_completa = os.path.join(ruta_directorio, nombre_archivo)

try:

os.makedirs(ruta_directorio, exist_ok=True)
with open(ruta_completa, "w") as archivo:

for argumento in argumentos:

archivo.write(argumento + "\n")

print(f"Argumentos guardados en '{ruta_completa}'")

except Exception as e:

print(f"Error al escribir en el archivo: {e}")

if __name__ == "__main__":

main()
Any help? Thanks

Solved! I need to put absolute path to python and it works! Thanks
Gribouillis likes this post
Reply
#3
You could start the batch file with subprocess.run. The batch file is executed via cmd.exe.

Small example with suppressing the CMD Terminal:
import subprocess


def run_batch(script: str):
    proc = subprocess.run(
        ["cmd.exe", "-C"],
        creationflags=subprocess.CREATE_NO_WINDOW,
        capture_output=True,
        input=script,
        encoding="latin1",
    )

    print("SDOUT:", proc.stdout)
    print()
    print("SDOUT:", proc.stderr)
    print()
    print(proc.returncode)


SCRIPT = """
echo Hello World
dir
"""

run_batch(SCRIPT)
And instead of inline the batch file, you could execute it from Python:
import subprocess
from pathlib import Path


def run_batch(script: Path):
    proc = subprocess.run(
        script,
        creationflags=subprocess.CREATE_NO_WINDOW,
        capture_output=True,
        encoding="latin1",
    )

    print("SDOUT:", proc.stdout)
    print()
    print("SDOUT:", proc.stderr)

    return proc.returncode == 0


# only absolute Paths do work with .bat-files.
batch_file = Path.home().joinpath("Desktop", "k.bat").absolute()
run_batch(batch_file)
Check, if the encoding latin1 is correct. I don't know if different language versions of windows uses different encodings for cmd.exe.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Get an FFMpeg pass to subprocess.PIPE to treat list as text file? haihal 2 1,243 Nov-21-2024, 11:48 PM
Last Post: haihal
  Problems passing arguments containing spaces to bash script and then on to python kaustin 6 9,561 Apr-03-2024, 08:26 PM
Last Post: deanhystad
  How to pass encrypted pass to pyodbc script tester_V 0 1,854 Jul-27-2023, 12:40 AM
Last Post: tester_V
  How to send data from a python application to an external application aditya_rajiv 1 3,119 Jul-26-2021, 06:00 AM
Last Post: ndc85430
  Possible to dynamically pass arguments to a function? grimm1111 2 3,062 Feb-21-2021, 05:57 AM
Last Post: deanhystad
  Why Pass Functions as arguments? muzikman 14 8,864 Jan-18-2021, 12:08 PM
Last Post: Serafim
  Keep Application running after Python script ends PEGylated_User 0 2,811 Nov-12-2020, 03:27 PM
Last Post: PEGylated_User
  how to pass arguments between pythons scripts? electricDesire 2 3,150 Oct-19-2020, 07:19 PM
Last Post: electricDesire
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 3,580 Sep-07-2020, 08:02 AM
Last Post: perfringo
  Web Form to Python Script to Text File to zip file to web wfsteadman 1 3,040 Aug-09-2020, 02:12 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020