Search code examples
pythoncmd

Run multiple commands in single cmd with some delay


I want to run multiple commands in a single cmd and i want in between command to have a delay.

I have the following code

import os

os.system('cmd /k "command1" & "command2" & "command3"')

How can i add some time.sleep between these commands?


Solution

  • Of the Many ways of doing this, this one is perhaps the simplest:

    import os
    
    os.system('cmd /K "command1 & timeout 30 & command2 & timeout 30 & command3"')
    

    This uses the timeout function present in the CMD environment, and allows the other commands to run correctly.

    Note: the CMD option /K will leave garbage shell sessions on the system, instead you should use /C as it will cause the CMD instance to terminate when all of the commands are completed or an error is encountered.

    ie:

    import os
    
    os.system('cmd /C "command1 & timeout 30 & command2 & timeout 30 & command3"')
    

    of course you might want to control the time in seconds for each timeout:

    eg:

    import os
    WaitSeconds1=30
    WaitSeconds2=90
    
    os.system('cmd /C "command1 & timeout '+WaitSeconds1+' & command2 & timeout '+WaitSeconds2+' & command3"')
    

    All of that said, I want to be sure you understand that CMD will not execute these commands in parallel, so if the timeout is to avoid parallel processing, instead of to wait for additional things register etc.

    I am aware that not every command waits to have it's work finished before exiting out (I'm looking at you, among others DiskPart! [Although, TBQF, Diskpart has valid reasons for being set up the way it is, it just needs to be improved for better feedback in scripting.) ).

    However if you know that isn't the case, you can just use:

    import os
    
    os.system('cmd /C "command1 & command2 & command3"')
    

    And, as mentioned by @Arty you can always replace the single ampersand & with a double ampersand && in any of these examples to only have it execute the next command when the previous command completes successfully, if that is a needed conditional. :)