Search code examples
python-3.xpowershellcmd

Use CMD inside Python


Good evening everyone, this is the first time I post here.

I have many codes I need to run in CMD but I'm not good at coding with CMD, so I want to use python to modify the code that I have to repeat often

for example

temp1 = ["C:/dir1", "C:/dir2", "C:/dir3"]
temp2 = ["1", "2", "3"]
for i, p in zip(temp1, temp2):
    os.system('7z -a "{}" C:/target/output"{}" -m5'.format(i, p))

With my code, I also need to see the Shell prompt, because some of the codes I do show a very long terminal data output that I want to monitor actively, I prefer to see it in the python terminal as an output, or print or something similar.

Thanks in advance, it is my first post hope it's clear.


Solution

  • os.system() implicitly uses cmd.exe on Windows (by passing the specified command line to cmd /c) and implicitly passes the command's output through to stdout.

    Therefore, your command should work in principle, though I recommend double-quoting the target path in full ("C:/target/output{}"), not just the substituted part (C:/target/output"{}")[1]:

    import os
    
    temp1 = ["C:/dir1", "C:/dir2", "C:/dir3"]
    temp2 = ["1", "2", "3"]
    for i, p in zip(temp1, temp2):
        os.system('7z -a "{}" "C:/target/output{}" -m5'.format(i, p))
    

    If you're running this code from a GUI script (a script invoked via pythonw.exe / pyw.exe), the console window created for each os.system() call automatically closes when the command finishes, which doesn't allow you to inspect the output after the fact. To address this, you have two options:

    • Append & pause to the command, which waits for keypress before closing the console window:
    import os
    
    temp1 = ["C:/dir1", "C:/dir2", "C:/dir3"]
    temp2 = ["1", "2", "3"]
    for i, p in zip(temp1, temp2):
        os.system('7z -a "{}" "C:/target/output{}" -m5 & pause'.format(i, p))
    
    • Invoke your command via cmd /k, which starts an interactive cmd.exe session that stays open after the command finishes; note that each such session then blocks further execution of your Python script until you manually close the console window in which the persistent cmd.exe session runs.
    import os
    
    temp1 = ["C:/dir1", "C:/dir2", "C:/dir3"]
    temp2 = ["1", "2", "3"]
    for i, p in zip(temp1, temp2):
        os.system('cmd /k " 7z -a "{}" "C:/target/output{}" -m5 "'.format(i, p))
    

    Note the unusual quoting (an outer "..." string in which embedded " aren't escaped), which is what cmd.exe supports, however.


    [1] Typically, this shouldn't make a difference, but you never know how programs parse their command line on Windows, and double-quoting an argument in full is more likely to work.