【问题标题】:Open Empty Command Prompt and Stay Open with Python打开空命令提示符并使用 Python 保持打开状态
【发布时间】:2025-12-27 13:55:16
【问题描述】:

我希望 python 打开一个空的命令提示符 (cmd.exe) 并让它保持打开状态而不运行任何东西。我希望命令提示符在新窗口中打开,并且此 python 代码继续运行。

我试过了:

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

还有:

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

还有:

os.system("start /wait C://Windows/System32/cmd.exe")

还有:

os.system("start /wait cmd /c")

以上都没有打开命令提示符。我还希望以后能够通过以下方式关闭它(使用 python):

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

感谢您的帮助。我无法在任何地方找到答案。 This 是最接近的,但这需要输入命令。我不希望之前输入命令。

【问题讨论】:

  • 对我来说,以下工作完美:os.system('cmd /C start cmd')os.system('cmd /C start')os.system('start cmd')os.system('start')
  • 顺便问一下:你为什么delete the other equal question 并发布一个新的??
  • @aschipfl 因为发布答案的人删除了它,在我复制代码之前,它不会得到更多关注。
  • 一开始要耐心点;好的答案可能需要一些时间。为了获得更多吸引力,请编辑和改进您关于 cmets 的原始问题帖子,而不是删除和重新发布!还可以考虑启动bounty。请注意,重新发布可能会吸引反对票和接近票...
  • @aschipfl 谢谢。下次我会记住这一点!

标签: python shell cmd os.system


【解决方案1】:

对我来说,这很有效(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()

【讨论】:

    【解决方案2】:

    我找到了一些方法来做到这一点。首先,有两种打开命令提示符的方法。一种是普通的 Windows 命令提示符。另一种方法是使用 python 作为输入打开它。两者都有几种方法。

    对于 Python 作为输入:

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

    “unique_name”是这样的,它可以用以下方式关闭:

    os.system('taskkill /F /IM "cmd.exe" /FI "WINDOWTITLE eq Unique_name"')
    

    以下也有效:

    os.system('cmd /C start cmd')

    os.system('cmd /C start')

    os.system('start cmd')



    对于 Windows 命令提示符:

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

    这可以关闭:

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

    【讨论】: