1. 程式人生 > >windows 10 python subprocess.Popen cmd 命令

windows 10 python subprocess.Popen cmd 命令

python 新建一個cmd視窗執行命令,並關閉視窗

import subprocess,time,psutil 
proc = subprocess.Popen("C:\\downloads\\b.bat",creationflags=subprocess.CREATE_NEW_CONSOLE) 
time.sleep(10) 

pobj = psutil.Process(proc.pid) 
# list children & kill them 
for c in pobj.
children(recursive=True): c.kill() pobj.kill()

b.bat 內容
ping -t baidu.com

10秒後ping關閉視窗
在這裡插入圖片描述

2,cmd 執行python 指令碼,並關閉建立的 cmd視窗

  • test03.py 指令碼
import subprocess,time,psutil 
command = "C:\\downloads\\b.bat"
proc = subprocess.Popen(command,creationflags=subprocess.CREATE_NEW_CONSOLE) 
time.
sleep(5) pobj = psutil.Process(proc.pid) # list children & kill them for c in pobj.children(recursive=True): c.kill() pobj.kill()
  • b.bat 指令碼
python "C:\\win10\\test01.py"
  • test01.py
import requests
from time import sleep
i = 0
while (i < 10):
    print (i)
    sleep(
1) i = i + 1 url = requests.get("http://www.baidu.com") status = url.status_code print (status)

在這裡插入圖片描述
參考:

  1. Can I close the CMD window that opened with subprocess.Popen in Python?
  2. Using subprocess to run Python script on Windows
  3. How to Create a Batch File to Run Python Script