Batch script to execute a Python script multiple times
<p>I need to run a Python script N times, so I created the following script:</p>

<pre><code>@ECHO OFF
cd PATH_TO_SCRIPT
@set port=5682
set /P INPUT=Number of servers: 
FOR /L %%I IN (1, 1, %INPUT%) DO (
    @set /a newport=%port%+1
    start cmd /k &gt; start python server.py -i 192.168.1.2 -p %newport%
)
pause
</code></pre>

<p>If I enter <strong>1</strong> as input value, such that there is only one iteration, the script works, but if I choose 2, the script only runs one instance of the server and tells me: "Unable to access file. The file is used from another process". What's wrong?</p>

<pre><code>@ECHO OFF
setlocal enabledelayedexpansion
cd PATH_TO_SCRIPT
set port=5682
set /P INPUT=Number of servers: 
set /a newport=%port%
FOR /L %%I IN (1, 1, %INPUT%) DO ( 
   set /a newport+=1
   start cmd /k &gt; start python server.py -i 192.168.1.2 -p !newport!
)
pause
</code></pre>

<p>Logic error : On each iteration, you are adding 1 to <code>PORT</code>, but <code>port</code> never changes. You need to initialise <code>newport</code> to the value of <code>port</code> and increment <code>newport</code>.</p>

<p>Minor style problem: <code>@</code> is not required after <code>@echo off</code>. <code>echo off</code> turns OFF command-reporting. <code>@</code> before a command turns command reporting OFF for <em>that command</em> only</p>

<p>Major problem : Please see the many, many articles on SO about <em>delayed expansion</em>. In essence, <code>%var%</code> refers to the value of <code>var</code> as it was set at the <strong>start</strong> of the loop and if you want to access the value as it changes within the loop, you need to invoke <code>delayedexpansion</code> and use <code>!var!</code></p>

<p>Your problem to fix: the <code>cmd /k</code> is not required, and the <code>&gt;</code> is, as pointed out already, bizarre.</p>

<p>Also, your logic would start numbering at 5683 because you add 1 <em>before</em> invoking the <code>start</code>. May or may not be a problem.</p>

python windows batch-file