Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Starting external Program in Python and blocking it's window to prevent focuschange

after searching for a long time I don’t a working solution. Here is my script:

import psutil
import time
import subprocess
import json
import requests
from datetime import datetime
from influxdb import InfluxDBClient

CLIENT = InfluxDBClient("grafana.i.3fu.de", "8086", "grafana", "test", "firewall")
MEASUREMENT = "arbeitspc"
REMOTE_EXE = "C:\\Users\\Gamienator\\AppData\\Roaming\\RemoteSensorMonitoring\\Remote Sensor Monitor.exe"

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

def findProcessIdByName(processName):
    '''
    Get a list of all the PIDs of a all the running process whose name contains
    the given string processName
    '''

    listOfProcessObjects = []

    #Iterate over the all the running process
    for proc in psutil.process_iter():
       try:
           pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])
           # Check if process name contains the given name string.
           if processName.lower() in pinfo['name'].lower() :
               listOfProcessObjects.append(pinfo)
       except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) :
           pass

    return listOfProcessObjects

def startProgram():
    SW_HIDE = 0
    info = subprocess.STARTUPINFO()
    info.dwFlags = subprocess.STARTF_USESHOWWINDOW
    info.wShowWindow = SW_HIDE
    exe = [REMOTE_EXE, "--gpuz=0", "--aida64=0", "--ohm=0"]
    subprocess.Popen(exe, startupinfo=info)
   

def sendToInflux():
    NOW = datetime.now()
    hwinfodata = requests.get('http://localhost:55555')
    data = hwinfodata.json()
    summarized = {}
    for d in data:
        name = "{}__{}".format(d['SensorClass'], d['SensorName']).replace(" ", "_")
        summarized[name]=d['SensorValue']

    json_body=[
        {
            "measurement": MEASUREMENT,
            "time": NOW,
            "fields" : summarized
        }
    ]
    CLIENT.write_points(json_body)


def main():
    startProgram()
    time.sleep(10)

    # Find PIDs od all the running instances of process that contains 'chrome' in it's name
    listOfProcessIds = findProcessIdByName('Remote Sensor Monitor.exe')

    if len(listOfProcessIds) > 0:
       #print('Process Exists | PID and other details are')
       for elem in listOfProcessIds:
           processID = elem['pid']
           sendToInflux()
           #print((processID ,processName,processCreationTime ))
           process = psutil.Process(processID)
           process.terminate()
    else :
       print('No Running Process found with given text')

if __name__ == '__main__':
   main()

My Goal is to push my HWInfo stats into an Grafana Board that I can look up on an different screen (a Raspberry Pi) Stats like FPS, Temps etc. The way I foudn out is, enabled HWinfo and starting Remote Sensor Monitor.exe from here which starts a small WebServer and give results as JSON. The only Problem is: starting the exe results into creating a new CMD Window:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This Python script will run every minute in the background, but as soon as it starts, my game for example gets minimized because the exe was started. Is there a way to that it over Python without showing the windows?

>Solution :

To make my comment an answer:

On Windows, you can use pythonw.exe (or rename your Python script to something.pyw) to start the Python interpreter without a console window.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading