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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

also, how do we pass multiple arguments?
@SuryaTej read this
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")

Comments

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.