Search code examples
pythoncmdsubprocesspython-os

How can I execute multiple commands in cmd in different lines of code in Python?


I am trying to run multiple commands in command prompt using Python, but I want to organize them into separete lines of code, so it's easier for me to read and edit later.

I started by using:

import os

os.system('cmd /c "command_1 & command_2 & command_3 & ... & command_n"')

But as I developed my program, I began to need more and more commands and it became annoying very quickly. So I tried a lot of different formats and even tried using the subprocess module, but to no avail, since I can't seem to be able to separate the commands.

Here are some examples that I tried, but FAILED:

- Separating them into different functions:

import os

os.system('cmd /k "command_1"')
os.system('cmd /k "command_2"')
...
os.system('cmd /c "command_n"')

This only executes the first command.


- Separating them into different lines:

import os

os.system(
'''
cmd /k "command_1 &
command_2 &
...
command_n"
'''
)
# I tried different variations of this, but none of them worked

These also execute only the first command, even when I try to put the "&" on the line below, or even with different formating. I tried passing each command as an argument, but this function can only get one.


Solution

  • You can make up the single string on multiple lines:

    os.system('cmd /c "'
       + 'command_1 & '
       + 'command_2 & '
       + 'command_3 & '
       ...
       + 'command_n"'
    )
    

    It's the same string, but formatted differently. Whereas the ''' multi-line string includes the line-breaks in the string, this one doesn't.

    Or you could write a multi-line string and remove the line breaks:

    os.system(
    '''
    cmd /k "command_1 &
    command_2 &
    ...
    command_n"
    '''.replace('\n', '')
    )