简体   繁体   English

打开空命令提示符并使用Python保持打开状态

[英]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. 我希望python打开一个空的命令提示符(cmd.exe),并使其保持打开状态,而不运行任何命令。 I want command prompt to open in a new window and this python code to continue running. 我想在新窗口中打开命令提示符,并且此python代码继续运行。

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: 我还希望稍后可以通过以下方式将其关闭(使用python):

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). 对我来说,这可行(Windows 10,Python 3.3.5和使用psutil库)。

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. 一种是普通的Windows命令提示符,另一种是通过以python作为输入打开它。 There are a few ways for both. 两种方式都有。

For Python as the input: 对于Python作为输入:

os.system('cmd.exe /C start "Unique_name" cmd.exe')

The "unique_name" is so that it can be closed with: “ unique_name”是这样的,因此可以使用以下命令将其关闭:

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: 对于Windows命令提示符:

os.startfile("C://Windows/System32/cmd.exe")

This can be closed with: 可以用以下方法关闭它:

os.system("taskkill /f /im  cmd.exe")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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