#HotFixes: OrchestratorProcessorStartStop, OrchestratorStartNotRunExplorerWhenRun, UIdesktopFixes, Orchestrator add ProcessStartIfNotStarted

dev-linux
Ivan Maslov 5 years ago
parent ae1e062430
commit c923087acb

@ -154,15 +154,15 @@ def Settings():
} }
}, },
{ {
"TimeHH:MMStart": "19:20", #Time [HH:MM] to trigger activity "TimeHH:MMStart": "12:40", #Time [HH:MM] to trigger activity
"TimeHH:MMStop": "19:20", "TimeHH:MMStop": "12:40",
"ActivityIntervalSeconds": 5, "ActivityIntervalSeconds": 2,
"WeekdayList": [1, 2, 3], #List of the weekday index when activity is applicable, Default [1,2,3,4,5,6,7] "WeekdayList": [1, 2, 3, 4, 5, 6, 7], #List of the weekday index when activity is applicable, Default [1,2,3,4,5,6,7]
"Activity":{ "Activity":{
"Type": "PythonStart", #Activity type "Type": "ProcessStartIfTurnedOff", #Activity type
"ModuleName": "CheckActivity", #Python function module name "CheckTaskName": "notepad.exe", #Python function module name
"FunctionName": "test_activity", #Python function name "Path": "notepad", #Python function name
"ArgList": ["TestArg1", "TestArg2"] #Input python function args "ArgList": [] #Input python function args
} }
} }
], ],
@ -218,7 +218,7 @@ def Settings():
#lFunction to call in subfiles #lFunction to call in subfiles
lSubmoduleFunctionName = "SettingsUpdate" lSubmoduleFunctionName = "SettingsUpdate"
#lSettingsPath = os.path.join(inSettingsFolderPath, "Settings") #lSettingsPath = os.path.join(inSettingsFolderPath, "Settings")
lSettingsPath = "\\".join(__file__.split("\\")[:-1]) lSettingsPath = "\\".join(os.path.join(os.getcwd(),__file__).split("\\")[:-1])
#lSettingsPath = os.path.join(os.getcwd(), "Settings") #lSettingsPath = os.path.join(os.getcwd(), "Settings")
#Lambda function to get files .py from settings folder except Settings.py #Lambda function to get files .py from settings folder except Settings.py
lFileList = [f for f in os.listdir(lSettingsPath) if os.path.isfile(os.path.join(lSettingsPath, f)) and f.split(".")[-1] == "py" and os.path.join(lSettingsPath, f) != __file__] lFileList = [f for f in os.listdir(lSettingsPath) if os.path.isfile(os.path.join(lSettingsPath, f)) and f.split(".")[-1] == "py" and os.path.join(lSettingsPath, f) != __file__]

@ -7,6 +7,7 @@ import sys
import subprocess import subprocess
import copy import copy
import importlib import importlib
import psutil
#Input arg #Input arg
# [ # [
# { # {
@ -38,6 +39,13 @@ import importlib
# #
# }, # },
# { # {
# "Type":"ProcessStartIfTurnedOff",
# "CheckTaskName":"", #Check if current task name is not active (then start process),
# "Path":"",
# "ArgList":[]
#
# },
# {
# "Type":"ProcessStop", # "Type":"ProcessStop",
# "Name":"", # "Name":"",
# "FlagForce":True, # "FlagForce":True,
@ -71,6 +79,7 @@ def Activity(inActivity):
inActivity["DateTimeUTCStringStart"] = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%dT%H:%M:%S.%f") inActivity["DateTimeUTCStringStart"] = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%dT%H:%M:%S.%f")
#Alias (compatibility) #Alias (compatibility)
lItem = inActivity lItem = inActivity
lCurrentDateTime = datetime.datetime.now()
########################################################### ###########################################################
#Обработка запроса на отправку команды на удаленную машину #Обработка запроса на отправку команды на удаленную машину
########################################################### ###########################################################
@ -138,11 +147,33 @@ def Activity(inActivity):
#Вид активности - запуск процесса #Вид активности - запуск процесса
#Запись в массив отработанных активностей #Запись в массив отработанных активностей
#Лог #Лог
mGlobalDict["Processor"]["LogList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processPath"], "activityStartDateTime":str(lCurrentDateTime)}) mGlobalDict["Processor"]["LogList"].append({"activityType":lItem["Type"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["Path"], "activityStartDateTime":str(lCurrentDateTime)})
#Запустить процесс #Запустить процесс
lItemArgs=[lItem["processPath"]] lItemArgs=[lItem["Path"]]
lItemArgs.extend(lItem["processArgs"]) lItemArgs.extend(lItem["ArgList"])
subprocess.Popen(lItemArgs,shell=True) subprocess.Popen(lItemArgs,shell=True)
#####################################
#ProcessStartIfTurnedOff
#####################################
if lItem["Type"]=="ProcessStartIfTurnedOff":
#Check if process running
#remove .exe from Taskname if exists
lCheckTaskName = lItem["CheckTaskName"]
if len(lCheckTaskName)>4:
if lCheckTaskName[-4:].upper() != ".EXE":
lCheckTaskName = lCheckTaskName+".exe"
else:
lCheckTaskName = lCheckTaskName+".exe"
#Check if process exist
if not CheckIfProcessRunning(lCheckTaskName):
#Вид активности - запуск процесса
#Запись в массив отработанных активностей
#Лог
mGlobalDict["Processor"]["LogList"].append({"activityType":lItem["Type"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["Path"], "activityStartDateTime":str(lCurrentDateTime)})
#Запустить процесс
lItemArgs=[lItem["Path"]]
lItemArgs.extend(lItem["ArgList"])
subprocess.Popen(lItemArgs,shell=True)
################################# #################################
#ProcessStop #ProcessStop
################################# #################################
@ -150,7 +181,7 @@ def Activity(inActivity):
#Вид активности - остановка процесса #Вид активности - остановка процесса
#часовой пояс пока не учитываем #часовой пояс пока не учитываем
#Сформировать команду на завершение #Сформировать команду на завершение
lActivityCloseCommand='taskkill /im '+lItem["processName"] lActivityCloseCommand='taskkill /im '+lItem["Name"]
#TODO Сделать безопасную обработку,если параметра нет в конфигурации #TODO Сделать безопасную обработку,если параметра нет в конфигурации
if lItem.get('FlagForce',False): if lItem.get('FlagForce',False):
lActivityCloseCommand+=" /F" lActivityCloseCommand+=" /F"
@ -158,7 +189,7 @@ def Activity(inActivity):
if lItem.get('User',"")!="": if lItem.get('User',"")!="":
lActivityCloseCommand+=f' /fi "username eq {lItem["User"]}"' lActivityCloseCommand+=f' /fi "username eq {lItem["User"]}"'
#Лог #Лог
mGlobalDict["Processor"]["LogList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processName"], "activityStartDateTime":str(lCurrentDateTime)}) mGlobalDict["Processor"]["LogList"].append({"activityType":lItem["Type"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["Name"], "activityStartDateTime":str(lCurrentDateTime)})
#Завершить процесс #Завершить процесс
os.system(lActivityCloseCommand) os.system(lActivityCloseCommand)
################################# #################################
@ -214,3 +245,17 @@ def ActivityListOrDict(inActivityListOrDict):
if type(inActivityListOrDict)==dict: if type(inActivityListOrDict)==dict:
#Dict activity #Dict activity
return Activity(inActivityListOrDict) return Activity(inActivityListOrDict)
def CheckIfProcessRunning(processName):
'''
Check if there is any running process that contains the given name processName.
'''
#Iterate over the all the running process
for proc in psutil.process_iter():
try:
# Check if process name contains the given name string.
if processName.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False;

@ -425,8 +425,6 @@ class RobotDaemonServer(Thread):
#httpd = HTTPServer(server_address, testHTTPServer_RequestHandler) #httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
# Logging # Logging
mGlobalDict["Logger"].info(f"Server init. Listen URL: {inServerAddress}, Listen port: {inPort}") mGlobalDict["Logger"].info(f"Server init. Listen URL: {inServerAddress}, Listen port: {inPort}")
# Запуск адреса в браузере
os.system("explorer http://127.0.0.1:8081")
#httpd.serve_forever() #httpd.serve_forever()
httpd = ThreadedHTTPServer(server_address, testHTTPServer_RequestHandler) httpd = ThreadedHTTPServer(server_address, testHTTPServer_RequestHandler)
#print('Starting server, use <Ctrl-C> to stop') #print('Starting server, use <Ctrl-C> to stop')

@ -1208,7 +1208,7 @@ def UIOSelector_Highlight(inUIOSelector):
UIO_Highlight(UIOSelector_Get_UIO(inUIOSelector)) UIO_Highlight(UIOSelector_Get_UIO(inUIOSelector))
else: else:
# Run function from other process with help of PIPE # Run function from other process with help of PIPE
lPIPEResuestDict = {"ModuleName": "UIDesktop", "ActivityName": "UIOSelector_Exist_Bool", lPIPEResuestDict = {"ModuleName": "UIDesktop", "ActivityName": "UIOSelector_Highlight",
"ArgumentList": [inUIOSelector], "ArgumentList": [inUIOSelector],
"ArgumentDict": {}} "ArgumentDict": {}}
# Отправить запрос в дочерний процесс, который отвечает за работу с Windows окнами # Отправить запрос в дочерний процесс, который отвечает за работу с Windows окнами
@ -1233,7 +1233,7 @@ def UIOSelector_FocusHighlight(inUIOSelector):
UIO_FocusHighlight(UIOSelector_Get_UIO(inUIOSelector)) UIO_FocusHighlight(UIOSelector_Get_UIO(inUIOSelector))
else: else:
# Run function from other process with help of PIPE # Run function from other process with help of PIPE
lPIPEResuestDict = {"ModuleName": "UIDesktop", "ActivityName": "UIOSelector_Exist_Bool", lPIPEResuestDict = {"ModuleName": "UIDesktop", "ActivityName": "UIOSelector_FocusHighlight",
"ArgumentList": [inUIOSelector], "ArgumentList": [inUIOSelector],
"ArgumentDict": {}} "ArgumentDict": {}}
# Отправить запрос в дочерний процесс, который отвечает за работу с Windows окнами # Отправить запрос в дочерний процесс, который отвечает за работу с Windows окнами

@ -90,7 +90,7 @@ def Settings():
#lFunction to call in subfiles #lFunction to call in subfiles
lSubmoduleFunctionName = "SettingsUpdate" lSubmoduleFunctionName = "SettingsUpdate"
#lSettingsPath = os.path.join(inSettingsFolderPath, "Settings") #lSettingsPath = os.path.join(inSettingsFolderPath, "Settings")
lSettingsPath = "\\".join(__file__.split("\\")[:-1]) lSettingsPath = "\\".join(os.path.join(os.getcwd(),__file__).split("\\")[:-1])
#lSettingsPath = os.path.join(os.getcwd(), "Settings") #lSettingsPath = os.path.join(os.getcwd(), "Settings")
#Lambda function to get files .py from settings folder except Settings.py #Lambda function to get files .py from settings folder except Settings.py
lFileList = [f for f in os.listdir(lSettingsPath) if os.path.isfile(os.path.join(lSettingsPath, f)) and f.split(".")[-1] == "py" and os.path.join(lSettingsPath, f) != __file__] lFileList = [f for f in os.listdir(lSettingsPath) if os.path.isfile(os.path.join(lSettingsPath, f)) and f.split(".")[-1] == "py" and os.path.join(lSettingsPath, f) != __file__]

@ -78,7 +78,13 @@ class App(tk.Frame):
self.rectx1, self.recty1) self.rectx1, self.recty1)
print('Rectangle ended') print('Rectangle ended')
print('##################Recognition result###########################') print('##################Recognition result###########################')
print(pytesseract.image_to_string(Image.open('screencapture_256_256.png'), lang='rus')) print(pytesseract.image_to_string(Image.open('screencapture_256_256.png'), lang='rus+eng'))
# Get verbose data including boxes, confidences, line and page numbers
print('##Get verbose data including boxes, confidences, line and page numbers##')
print(pytesseract.image_to_data(Image.open('screencapture_256_256.png'), lang='rus+eng'))
print('##Get information about orientation and script detection##')
# Get information about orientation and script detection
print(pytesseract.image_to_osd(Image.open('screencapture_256_256.png'), lang='rus+eng'))
if __name__ == "__main__": if __name__ == "__main__":
root = tk.Tk() root = tk.Tk()

Loading…
Cancel
Save