windows 10 python subprocess.Popen cmd 命令

版权声明:本文为博主原创文章,可以自由转载。 https://blog.csdn.net/u010953692/article/details/83831192

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

猜你喜欢

转载自blog.csdn.net/u010953692/article/details/83831192