Reputation: 497
I want python to open an empty Command Prompt (cmd.exe) and leave it open without running anything. I want command prompt to open in a new window and this python code to continue running.
I have tried:
os.system("start C://Windows/System32/cmd.exe")
And:
os.system("C://Windows/System32/cmd.exe")
And:
os.system("start /wait C://Windows/System32/cmd.exe")
And:
os.system("start /wait cmd /c")
None of the above left Command Prompt open. I also want to be able to close it later (with python) by using:
os.system("taskkill /f /im cmd.exe")
Thanks for any help. I couldn't find an answer to this anywhere. This was the closest but this needed a command to be entered. I don't want a command to be entered before.
Upvotes: 1
Views: 1821
Reputation: 497
I found out a few ways to do this. Firstly, there are 2 ways of opening command prompt. One is the normal Windows Command Prompt.The other way is by opening it with python as the input. There are a few ways for both.
For Python as the input:
os.system('cmd.exe /C start "Unique_name" cmd.exe')
The "unique_name" is so that it can be closed with:
os.system('taskkill /F /IM "cmd.exe" /FI "WINDOWTITLE eq Unique_name"')
The following also work:
os.system('cmd /C start cmd')
os.system('cmd /C start')
os.system('start cmd')
For Windows Command Prompt:
os.startfile("C://Windows/System32/cmd.exe")
This can be closed with:
os.system("taskkill /f /im cmd.exe")
Upvotes: 1
Reputation: 2947
For me, this worked (Windows 10, Python 3.3.5 and using the psutil library).
import psutil
import subprocess
import time
import os
p = subprocess.Popen("start /wait cmd.exe", shell=True)
# the pid of p is the pid of the shell, so let's get the shell's children,
# i.e. the opened cmd.exe window
p2 = psutil.Process(p.pid)
# there should be exactily one child
# but it may not have been started yet
while True:
children = p2.children()
if children:
break
print("no children yet")
time.sleep(0.01)
print(children)
time.sleep(5)
for child in children:
child.kill()
p.wait()
Upvotes: 1