https://docs.python.org/3/library/subprocess.html
import subprocess command = "ipconfig" subprocess.run( command, # 终端命令 shell=True # 允许执行shell程序 )
import subprocess import time command = "notepad.exe" notepad_process = subprocess.Popen( # 启动记事本 command, # 终端命令 ) time.sleep(3) # 等待3秒 notepad_process.kill() # 销毁进程
import subprocess command = "python.exe" open_process = subprocess.Popen( # 和命令交互 command, # 终端命令 stdin=subprocess.PIPE, # 输入 stdout=subprocess.PIPE, # 输出 stderr=subprocess.PIPE, # 错误 # encoding="gbk" # 编码格式,不指定的话,就是二进制编码 ) open_process.stdin.write("print('第1句话')\n".encode()) # 输入新命令 open_process.stdin.write("print('第2句话')\n".encode()) open_process.stdin.write("print('第3句话')\n".encode()) open_process.stdin.write("print(10/0)\n".encode()) open_process.stdin.close() # 关闭输入管道 cmd_out = open_process.stdout.read() # 读取信息,并返回值 open_process.stdout.close() # 关闭输出管道 print("输出:", cmd_out.decode(encoding="gbk")) cmd_error = open_process.stderr.read() open_process.stderr.close() # 关闭错误管道 print("错误:", cmd_error.decode(encoding="gbk"))