使用Python编写一个CMD脚本来实现进程的启动和停止
发布时间:2023-12-14 22:52:36
在Python中,可以使用subprocess模块来执行CMD脚本。下面是一个示例脚本,可以用于启动和停止进程:
import subprocess
import time
def start_process(process_name):
# 检查进程是否已经在运行
if check_process(process_name):
print(f"The process {process_name} is already running.")
return False
try:
# 启动进程
subprocess.Popen(process_name)
print(f"The process {process_name} has been started successfully.")
return True
except Exception as e:
print(f"Failed to start the process {process_name}. Error: {e}")
return False
def stop_process(process_name):
# 检查进程是否在运行
if not check_process(process_name):
print(f"The process {process_name} is not running.")
return False
try:
# 停止进程
subprocess.call(f"taskkill /F /IM {process_name}", shell=True)
print(f"The process {process_name} has been stopped successfully.")
return True
except Exception as e:
print(f"Failed to stop the process {process_name}. Error: {e}")
return False
def check_process(process_name):
# 检查进程是否在运行
result = subprocess.run(f"tasklist | findstr {process_name}", shell=True, capture_output=True)
return process_name.encode() in result.stdout
# 使用例子
if __name__ == "__main__":
# 启动进程
start_process("notepad.exe") # 启动记事本
time.sleep(5) # 等待5秒
# 停止进程
stop_process("notepad.exe") # 停止记事本
在上述示例中,我们定义了三个函数:
1. start_process(process_name): 使用subprocess.Popen启动进程。
2. stop_process(process_name): 使用subprocess.call调用CMD命令taskkill来停止进程。
3. check_process(process_name): 使用subprocess.run执行CMD命令tasklist并使用findstr进行进程名的过滤,以检查进程是否在运行。
在使用例子部分,我们通过调用start_process函数来启动记事本进程(可以将notepad.exe替换为你要启动的进程),然后使用time.sleep等待5秒,最后通过调用stop_process函数来停止记事本进程。
请注意,在Windows操作系统中,taskkill命令是用于终止进程的命令。如果在其他操作系统上运行该脚本,需要根据操作系统的不同使用相应的命令来实现进程的启动和停止。
