0

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.

4
  • 1
    Add the full path to the print file in your batch script.
    – OldBoy
    Commented Jul 1 at 8:18
  • 1
    Also do some research about "current working directory" and how that is relevant for relative paths, which is almost certainly the issue you're facing (it's a valid assumption, but you should've at least included the line related to the prn file, we should not be forced to make guesses). Commented Jul 1 at 8:29
  • Well, apparently your batch file is not WORKING as well as you expected. Also learn about minimal reproducible examples so we don't have to guess.
    – Jeyekomon
    Commented Jul 1 at 8:55
  • 1
    @Nico The usage of "%~dp0exaple.prn" instead of just exaple.prn would have solved the problem too. %~dp0 is drive and path of argument 0 which is the batch file name argument string. %~dp0 expands therefore to full directory path of the batch file always ending with a backslash which is concatenated with the file name expected in the batch file directory and not in the current working directory.
    – Mofi
    Commented Jul 1 at 10:25

1 Answer 1

1

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

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.