Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a command prompt along with a command to run using a python script?

Tags:

python

windows

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?

like image 206
Surya Tej Avatar asked Mar 02 '26 02:03

Surya Tej


1 Answers

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

like image 153
Tanmay jain Avatar answered Mar 04 '26 14:03

Tanmay jain