簡體   English   中英

打開空命令提示符並使用Python保持打開狀態

[英]Open Empty Command Prompt and Stay Open with Python

我希望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")

謝謝你的幫助。 我在任何地方都找不到答案。 是最接近的,但這需要輸入命令。 我不希望在此之前輸入命令。

對我來說,這可行(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()

我發現了幾種方法。 首先,有兩種打開命令提示符的方式。 一種是普通的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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM