2

I tried the below approach to open a command prompt and run a sample command. But it immediately closes:

import os
# as of now i am just passing cd /../, later will be changing to a different command
os.system("start /wait cmd /c {cd /../}")

I also tried this way, but this opens two command shells:

import os
os.system("start /B start cmd.exe @cmd /k cd /d D:")

Two commands shell are being opened

Is it possible to just open one command prompt and run the command?

colidyre
  • 4,170
  • 12
  • 37
  • 53
Surya Tej
  • 1,342
  • 2
  • 15
  • 25

2 Answers2

7
import subprocess

cmd = subprocess.Popen('cmd.exe /K cd /') 

#subprocess.Popen('cmd.exe /K netstat') # run cmd commands like netstat,..etc
#subprocess.Popen('cmd.exe /K python') # open cmd in  Python live interpreter mode
#subprocess.Popen('cmd.exe /K my_script.py') # run your python script

read more https://docs.python.org/3/library/subprocess.html#subprocess.Popen

Tanmay jain
  • 814
  • 6
  • 11
3

The CMD window will run the commands you give it and then immediately close on completion, if you want to keep the window open you need to send a pause command:

os.system("YOUR COMMAND")

os.system("pause")

Community
  • 1
  • 1
Jerome Paddick
  • 399
  • 1
  • 14