4

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.

Toykan Ozdeger
  • 139
  • 2
  • 3
  • 12
  • Possible duplicate of [running multiple bash commands with subprocess](https://stackoverflow.com/questions/17742789/running-multiple-bash-commands-with-subprocess) – JD D Apr 30 '19 at 12:29
  • It explains how to run them in parallel not one after another @JD D – Toykan Ozdeger Apr 30 '19 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!? – B. Go Apr 30 '19 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 – B. Go Apr 30 '19 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. – JD D Apr 30 '19 at 12:51
  • Precision in language really does matter. What is meant by the phrase "command prompt"? A command prompt is a string that is presented by a shell to the user. It simply doesn't make any sense to say "run a command in command prompt". I suppose it means "send a string to a shell for execution", and if you use precise language to describe the problem you are trying to solve I believe the solution becomes trivial. – William Pursell Aug 13 '23 at 15:56

2 Answers2

0

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

p = subprocess.Popen(["start", "cmd", "/k", "cd Desktop && cd Programs"], shell = True)
-1

Popen(["start", "cmd", "/k" "cd Desktop && cd Programs"], shell=True)