0

I'm having an issue with running a pretty simple Python script from a Windows batch file.

The Batch Code is:

"C:\Python27\python.exe" "V34_File_Converter.py" %*
pause

where the "V34_File_Converter.py" file is located in the same folder as the batch file.

The Python Code is:

import os,sys
import psse34
import psspy

print('we are in the program')

args_num = len(sys.argv) - 1

psspy.psseinit()

for f_name in sys.argv[1:]:

    print f_name

    psspy.read(0,f_name)
    f_name_out = os.path.splitext(f_name)[0] + "_V34.RAW"
    psspy.rawd_2(0,1,[1,1,1,0,0,0,0],0,f_name_out)

The main issue is when I double click the Batch file, the program runs fine, printing the first message and initializing the PSSE program. However, when I drag and drop files onto the batch script, I get the following Error:

C:\Python27\python.exe: can't open file 'V34_File_Converter.py': [Errno 2] No such file or directory 

Which is strange, considering it finds that file no problem if no other arguments are passed.

Thanks for any help!

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118

1 Answers1

0

The Python script file V34_File_Converter.py is obviously in the directory of the batch file because of referenced in batch file without file path. The batch file directory is set as current directory by Windows before starting cmd.exe to process the batch file on double clicking the batch file. There are two exceptions:

  1. The batch file is started with using Run as administrator instead of double clicking it resulting often in setting %SystemRoot%\System32 as current directory.
  2. A double clicked batch file is stored on a network resource accessed using a UNC path in which case %SystemRoot% is set by default as current directory.

But batch files can be in general executed from any other directory, too. Therefore it is advisable to reference other files in a batch file with their full qualified file names.

Open a command prompt, run call /? and read the output help explaining how the batch file arguments can be referenced from within a batch file. Argument 0 is always the string used to start processing of the batch file.

The solution here is:

"C:\Python27\python.exe" "%~dp0V34_File_Converter.py" %*

%~dp0 references drive and path of argument 0 which is the batch file itself, i.e. the path to the batch file directory which obviously contains also the Python script file. The path string referenced with %~dp0 always ends with a backslash. For that reason no additional backslash should be used on concatenating this path with a file or folder name.

See also:

Mofi
  • 46,139
  • 17
  • 80
  • 143