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

时间:2017-06-02 10:57:32

标签: python shell cmd os.system

我希望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是最接近的,但这需要输入一个命令。我以前不想要输入命令。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

我发现了几种方法。首先,有两种方法可以打开命令提示符。一个是正​​常的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")
相关问题