Hide the console while using os.system or subprocess.call in Python

si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
#si.wShowWindow = subprocess.SW_HIDE # default
subprocess.call('taskkill /F /IM exename.exe', startupinfo=si)
CREATE_NO_WINDOW = 0x08000000
subprocess.call('taskkill /F /IM exename.exe', creationflags=CREATE_NO_WINDOW)
DETACHED_PROCESS = 0x00000008
subprocess.call('taskkill /F /IM exename.exe', creationflags=DETACHED_PROCESS)

References
https://stackoverflow.com/questions/7006238/how-do-i-hide-the-console-when-i-use-os-system-or-subprocess-call

Encoding of readAllStandardOutput() QProcess

    ...
    output = bytearray(self.process.readAllStandardOutput())
    output = output.decode(self.GetCMD_Encoding())
    print (output)

def GetCMD_Encoding(self):

    CMD = QProcess(self)
    CMD.setProcessChannelMode(QProcess.MergedChannels)
    CMD.start("C:\Windows\System32\chcp.com")
    CMD.waitForReadyRead()
    output = bytearray(CMD.readAllStandardOutput())
    output = output.decode("ascii")
    output = output[18:]
    return "cp" + output

References
https://stackoverflow.com/questions/41761132/pyqt-qprocess-readallstandardoutput-encoding
https://stackoverflow.com/questions/57663191/how-to-convert-a-qbytearray-to-a-python-string-in-pyside2

Get return value and PID of spawned process using QProcess

import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QProcess

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    command = "./testCommand.py"
    args = [""]

    #"regular" startDetached : give two arguments, get a boolean
    process=QProcess()
    re=process.startDetached("ls",["."])
    print(re)
    print(type(re))

    #"overload" startDetached : give three arguments, get a tuple(boolean,PID)
    process2=QProcess()
    re,pid=process2.startDetached("ls",["."],".")
    print(re,pid)
    print(type(re),type(pid))

References
https://stackoverflow.com/questions/31519215/pyqt4-qprocess-startdetached-cant-get-return-value-and-pid-of-spawned-proce

Use QProcess to run a program

if self.mosquitto_process is None:
    self.mosquitto_process = QProcess()
self.mosquitto_process.start("mosquitto.cmd")
self.port = utils.pick_free_port()
    _logger().debug('starting server process: %s',
                    ' '.join([self._interpreter, server.__file__,
                              str(self.port)]))
    self._process = QtCore.QProcess()
    self._process.readyRead.connect(self._on_ready_read)
    self._process.setProcessChannelMode(self._process.MergedChannels)
    self._process.finished.connect(self._on_finished)
    self._process.stateChanged.connect(self._on_state_changed)
    self._process.start(
        self._interpreter, (server.__file__, str(self.port)))
proc = QProcess()
    proc.start(*py_proc('print("Hello World")'))
    dev = qtutils.PyQIODevice(proc)
    assert not dev.closed
    with pytest.raises(OSError) as excinfo:
        dev.seek(0)
    assert str(excinfo.value) == 'Random access not allowed!'
    with pytest.raises(OSError) as excinfo:
        dev.tell()
    assert str(excinfo.value) == 'Random access not allowed!'
    proc.waitForFinished(1000)
    proc.kill()
    assert bytes(dev.read()).rstrip() == b'Hello World'

References
https://programtalk.com/python-examples/PyQt5.QtCore.QProcess/

Python timestamp to datetime and vice-versa

Python timestamp to datetime

from datetime import datetime

timestamp = 1545730073
dt_object = datetime.fromtimestamp(timestamp)

print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))

Python datetime to timestamp

from datetime import datetime

# current date and time
now = datetime.now()

timestamp = datetime.timestamp(now)
print("timestamp =", timestamp)

References
https://www.programiz.com/python-programming/datetime/timestamp-datetime

Check if a process is running by name and find it’s Process ID in Python using psutil

Check if a process is running

import psutil
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;
# Check if any chrome process was running or not.
if checkIfProcessRunning('chrome'):
    print('Yes a chrome process was running')
else:
    print('No chrome process was running')

Find PID (Process ID) of a running process by Name

import psutil
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;
# Find PIDs od all the running instances of process that contains 'chrome' in it's name
listOfProcessIds = findProcessIdByName('chrome')
if len(listOfProcessIds) > 0:
   print('Process Exists | PID and other details are')
   for elem in listOfProcessIds:
       processID = elem['pid']
       processName = elem['name']
       processCreationTime =  time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time']))
       print((processID ,processName,processCreationTime ))
else :
   print('No Running Process found with given text')

References
https://thispointer.com/python-check-if-a-process-is-running-by-name-and-find-its-process-id-pid/

*args and **kwargs in Python

*args

# Python program to illustrate 
# *args for variable number of arguments
def myFun(*argv): 
  for arg in argv: 
    print (arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') 
# Python program to illustrate 
# *args with first extra argument
def myFun(arg1, *argv):
  print ("First argument :", arg1)
  for arg in argv:
    print("Next argument through *argv :", arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

**kwargs

# Python program to illustrate 
# *kargs for variable number of keyword arguments

def myFun(**kwargs): 
  for key, value in kwargs.items():
    print ("%s == %s" %(key, value))

# Driver code
myFun(first ='Geeks', mid ='for', last='Geeks') 
# Python program to illustrate **kargs for 
# variable number of keyword arguments with
# one extra argument.

def myFun(arg1, **kwargs): 
  for key, value in kwargs.items():
    print ("%s == %s" %(key, value))

# Driver code
myFun("Hi", first ='Geeks', mid ='for', last='Geeks') 

References
https://www.geeksforgeeks.org/args-kwargs-python/