How to open a new cmd window and execute for-loop in it?

I have a test.cmd file with the following command:

call "cmd /c start echo foo && pause" call "cmd /c start for /l %%x in (0, 1, 2) do python test.py config%%x" 

The first command works fine and shows that the general approach should work. The second with the for loop causes me problems.

When I run this command directly in the CMD window (only with the% symbol before the iterator), it runs my python script "test.py" in a new CMD window 3 times in a loop, as expected.

When I run the same command from my test.cmd (this time with two% of course), a new CMD window appears and disappears right away. I do not receive error messages and cannot receive a new window.

I suspect that I need to make a few more encodings, but I can not understand the correct syntax. What should I change to get this for the loop to run from my test.cmd?

+6
source share
3 answers

if you insist on using call , there is another level of parsing, so in a batch file you should use:

 call "cmd /k start for /l %%%%i in (1,1,10) do echo %%%%i" 

(replace /c with /k to see the result)

+5
source

try the following:

 call "cmd /c for /l %x in (0, 1, 2) do @python test.py config%x" 

when you execute loops on the command line, you need one percent character. And you need to remove the start command after cmd /c , because for is the cmd internal command. @ intended to suppress the printing of the prompt value at each iteration.

+2
source

This answer addresses the main question that is listed in the header of your message, not the code you provided.


To start the for loop in a separate window ( cmd ), the start command is required. In addition, an explicit instance of cmd must be specified in order to avoid problems with start when calling internal commands (for example, brackets can cause errors), and also have control over what happens with the new window after the cycle is completed.

The following command line executes the for loop in a new cmd window, which remains open after the loop ends (very useful for debugging):

 start "" /WAIT cmd /K "for /L %%X in (0,1,2) do echo %%X" 

Type exit in a new window to close it. To automatically close a new window, replace /K with /C

If you do not want your main (calling) script package to wait for the loop to complete and close a new window, remove the /WAIT switch. This launches the command line, but the main script immediately continues execution. This allows you to run multiple for loops in separate windows at the same time.


This method is not limited to just calling for loops.

+1
source

All Articles