6

I need to run a series of commands in command prompt and I want to automate this process. I can run a command in command prompt using Python code:

import os
os.system("start /B start cmd.exe @cmd /k {command}")

OR

import os
import subprocess
p = subprocess.Popen(["start", "cmd", "/k", "command"], shell = True)

However, after executing a command, I cannot write another command to the same command prompt. Is there a way to do this?

The thread Calling an external command in Python is similar but I don't think it explains how to write a new command to the same command prompt after the one before finishes executing

Also, as I understand running multiple bash commands with subprocess explains how to run commands in parallel not one after each other.

6
  • 1
    Possible duplicate of running multiple bash commands with subprocess Commented Apr 30, 2019 at 12:29
  • It explains how to run them in parallel not one after another @JD D Commented Apr 30, 2019 at 12:37
  • 1
    Why using Python, and not any kind of shell script directly? As you may end up having to launch a shell script from Python anyway!? Commented Apr 30, 2019 at 12:45
  • 3
    You can always run command1; command2; command3... or with & or && if you want to stop on error... depending on your command line shell Commented Apr 30, 2019 at 12:46
  • 1
    @ToykanOzdeger look at the answer from "admenva", it shows how to run commands one after another. The answer from "FrancisWolcott" suggests just chaining commands using && which should work for you as well. Commented Apr 30, 2019 at 12:51

1 Answer 1

-1

you can insert the '&' symbol (or other symbols, such as '&&' for example:

p = subprocess.Popen(["start", "cmd", "/k", "cd Desktop && cd Programs"], shell = True)
Sign up to request clarification or add additional context in comments.

2 Comments

I am wondering if there is a guarantee that each function will start after the previous one finishes, in this case.
&& goes one step further. The second command is run only if the first has finished succesfully, i.e. ERRORLEVEL=0, see web.archive.org/web/20060412075633/https://www.microsoft.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.