Skip to content

Commit 60a687b

Browse files
authored
Merge pull request #33 from botcity-dev/ENH/adds-methods-to-find-and-terminate-process
ENH: Adds the find_process method and terminate_process method
2 parents 94f4f37 + 733202d commit 60a687b

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

botcity/core/bot.py

+36-1
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,19 @@
22
import multiprocessing
33
import os
44
import platform
5+
import psutil
56
import random
67
import subprocess
78
import time
89
import webbrowser
9-
from typing import Union
10+
from typing import Union, List
11+
1012

1113
import pyperclip
1214
from botcity.base import BaseBot, State
1315
from botcity.base.utils import is_retina, only_if_element
1416
from PIL import Image, ImageGrab
17+
from psutil import Process
1518
from pynput.keyboard import Controller as KbController
1619
from pynput.keyboard import Key
1720
from pynput.mouse import Controller as MouseController
@@ -443,6 +446,38 @@ def find_text(self, label, x=None, y=None, width=None, height=None, *, threshold
443446
return self.find_until(label, x, y, width, height, threshold=threshold, matching=matching,
444447
waiting_time=waiting_time, best=best, grayscale=True)
445448

449+
def find_process(self, name: str = None, pid: str = None) -> List[Process]:
450+
"""
451+
Find a process by name or PID
452+
453+
Args:
454+
name (str): The process name.
455+
pid (str) or (int): The PID (Process Identifier).
456+
457+
Return:
458+
process (psutil.Process): A Process instance.
459+
"""
460+
for process in psutil.process_iter():
461+
try:
462+
if (name is not None and name in process.name()) or \
463+
(pid is not None and process.pid == pid):
464+
return process
465+
except (psutil.NoSuchProcess, psutil.AccessDenied):
466+
pass
467+
return None
468+
469+
def terminate_process(self, process: Process):
470+
"""
471+
Terminate the process via the received Process object.
472+
473+
Args:
474+
process (psutil.Process): The process to terminate.
475+
"""
476+
process.terminate()
477+
process.wait(10)
478+
if process.is_running():
479+
raise Exception("Terminate process failed")
480+
446481
def get_last_element(self):
447482
"""
448483
Return the last element found.

requirements.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ pyperclip
33
opencv-python
44
python-xlib
55
pywinauto
6-
pynput
6+
pynput
7+
psutil

0 commit comments

Comments
 (0)