1

I developed the following loop for running the model with different rainfall ensemble using a loop. The script is working properly except for the execution process of my .bat file.

import os
import glob
import subprocess

ws = (r'C:\Users\Wahid Hussainzada\Desktop\Takahashi_2018_9_test')
os.chdir(ws)
myFile = glob.glob('*.txt')
myModel = glob.glob('2cdrmv3.bat')


for i in myFile:
    if i.startswith('rain'):
        print(i)
        myBat = open(ws+'\wahid.bat','w+')
        myBat.write('cdrmv3.exe param1.txt param2.txt param3.txt param4.txt bsndir.txt slope.txt length.txt order.txt takahashi_landuse.txt takahashi_acc.txt 0 # 1 takahashi_thiessen.txt 13 '+str(i) +' 0 1 out_'+str(i) +' 0 outgrid\outa2 outgrid\outb')
        myBat.close()
        subprocess.call('C:\Users\Wahid Hussainzada\Desktop\Takahashi_2018_9_test\wahid.bat')
    else:
        print("Other txt files than rain files")
            
Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
  • See documentation for `subprocess.run` (https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.run). If you specify `shell=True` the command will be run using a shell. But you need to be aware of the security considerations if you specify shell=True (https://docs.python.org/3/library/subprocess.html?highlight=subprocess#security-considerations) – yasouser Mar 03 '21 at 03:43

2 Answers2

1

try using string literals

subprocess.call(r'C:\Users\Wahid Hussainzada\Desktop\Takahashi_2018_9_test\wahid.bat')

you might have to do something like

cmd = r'C:\Windows\System32\cmd.exe'
script = r'C:\Users\Wahid Hussainzada\Desktop\Takahashi_2018_9_test\wahid.bat'
subprocess.call([cmd,script])
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Based on @Joran Beasley answer the code can work with a minor revision as below:

cmd = r'C:\Windows\System32\cmd.exe'
script = r'Working directory\*.bat'
subprocess.call([script,cmd])