简体   繁体   中英

Open Empty Command Prompt and Stay Open with Python

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.

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()

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM