Search code examples
pythonbatch-filepyqt5

Unable to execute batch file by Python program


I have a WORKING batch file that I want to execute by my Python program. here is the portion of program related to that task:

def execute_batch_file(self):
    batch_file_path = r'C:\Users\UTENTE\Desktop\Programmi compilati Python\OP10\prova.bat'
    subprocess.Popen(batch_file_path, shell=True)

when I run the program I get the error message "Cannot open exaple.prn for reading". Again, if I execute the batch file manually I have no issue whatsoever. It does work fine. When I run it by my program I get the message above. For info, the batch file lunches an "lpr" command for a ".prn" file to be printed.

Any clue about the issue?

Thanks alot.


Solution

  • add the cwd keyword argument to subprocess.Popen and pass bat file directory to it.

    def execute_batch_file(self):
        batch_file_path = r'C:\Users\UTENTE\Desktop\Programmi compilati Python\OP10\prova.bat';
        
        # get bat file dir and name
        batch_file_name = os.path.basename(batch_file_path)
        batch_file_dir = os.path.dirname(batch_file_path)
    
    
        subprocess.Popen(batch_file_name, cwd=batch_file_dir, shell=True)
    

    don't forget to import os

    I learnt from this answer https://stackoverflow.com/a/21406995/21962459