Return a JSON response using Flask in Python

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/get-json')
def hello():
    return jsonify(hello='world') # Returns HTTP Response with {"hello": "world"}
person = {'name': 'Alice', 'birth-year': 1986}
return jsonify(person)
@app.route("/")
def index():
    return flask.jsonify(response_value_1=1,response_value_2="value")

References
https://riptutorial.com/flask/example/5831/return-a-json-response-from-flask-api
https://www.kite.com/python/answers/how-to-return-a-json-response-using-flask-in-python

Make a PyQT window bring to the front

from win32gui import SetWindowPos
import win32con

SetWindowPos(window.winId(),
             win32con.HWND_TOPMOST, # = always on top. only reliable way to bring it to the front on windows
             0, 0, 0, 0,
             win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW)
SetWindowPos(window.winId(),
             win32con.HWND_NOTOPMOST, # disable the always on top, but leave window at its top position
             0, 0, 0, 0,
             win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW)
window.raise_()
window.show()
window.activateWindow()

References
https://stackoverflow.com/questions/12118939/how-to-make-a-pyqt4-window-jump-to-the-front

How to send emoji in Python telegram bot

client.send_message(chat, 'ūüėČ')
client.send_message(chat, '\U0001F609')

If you prefer to use text replacements in your code, install the emoji package:

import emoji
client.send_message(chat, emoji.emojize(':wink:'))

References
https://stackoverflow.com/questions/57549311/python-telegram-telethon-how-to-send-emoji
https://pypi.org/project/emoji/
https://apps.timwhitlock.info/emoji/tables/unicode
https://www.webfx.com/tools/emoji-cheat-sheet/

PyInstaller-built Windows EXE fails with multiprocessing

Enabling --onedir multiprocessing support on Windows (does NOT work with --onefile on Windows, but otherwise safe on all platforms/configurations):

if __name__ == '__main__':
    # On Windows calling this function is necessary.
    multiprocessing.freeze_support()

Enabling --onefile multiprocessing support on Windows (safe on all platforms/configurations, compatible with --onedir):

import multiprocessing.forking
import os
import sys

class _Popen(multiprocessing.forking.Popen):
    def __init__(self, *args, **kw):
        if hasattr(sys, 'frozen'):
            # We have to set original _MEIPASS2 value from sys._MEIPASS
            # to get --onefile mode working.
            os.putenv('_MEIPASS2', sys._MEIPASS)
        try:
            super(_Popen, self).__init__(*args, **kw)
        finally:
            if hasattr(sys, 'frozen'):
                # On some platforms (e.g. AIX) 'os.unsetenv()' is not
                # available. In those cases we cannot delete the variable
                # but only set it to the empty string. The bootloader
                # can handle this case.
                if hasattr(os, 'unsetenv'):
                    os.unsetenv('_MEIPASS2')
                else:
                    os.putenv('_MEIPASS2', '')

class Process(multiprocessing.Process):
    _Popen = _Popen

# ...

if __name__ == '__main__':
    # On Windows calling this function is necessary.
    multiprocessing.freeze_support()

    # Use your new Process class instead of multiprocessing.Process

References
https://stackoverflow.com/questions/24944558/pyinstaller-built-windows-exe-fails-with-multiprocessing

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/