简体   繁体   中英

Batch script to execute a Python script multiple times

I need to run a Python script N times, so I created the following script:

@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 > start python server.py -i 192.168.1.2 -p %newport%
)
pause

If I enter 1 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?

@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 > start python server.py -i 192.168.1.2 -p !newport!
)
pause

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

Minor style problem: @ is not required after @echo off . echo off turns OFF command-reporting. @ before a command turns command reporting OFF for that command only

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

Your problem to fix: the cmd /k is not required, and the > is, as pointed out already, bizarre.

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

As pointed out already, in your FOR loop, %newport% resolves to [empty] upon execution. It's because newport isn't set until AFTER cmd resolves %newport%, since the entire FOR loop is one statement. In other words, %newport% gets resolved before the commands in the loop are executed, which means it's not set yet, and /p gets nothing. So presumably it uses the same port each time.

You don't have to use delayed expansion, though. You could just use your FOR /L iterator (%%I). I think this would be simpler.

@ECHO OFF & SETLOCAL
CD PATH_TO_SCRIPT
SET /P INPUT=Number of servers: 
SET /A END=5682+%INPUT%-1
FOR /L %%I IN (5682, 1, %END%) DO ( 
   START python server.py -i 192.168.1.2 -p %%I
)
PAUSE

Also, I agree that it is strange that you're redirecting the output to a file named start. I think you must have been trying to do something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM