Using Qt Resource in Subprocess command

I compile my Qt Resource Collection (QRC) and import it in my Python project, now I would like to be able to access a file in my QRC using subprocess. How can I do this?

I tried this below, but it does not access the compiled QRC…

import application_rc

test = QUrl("qrc:///resources/sounds/LRMonoPhase4.wav").path()

process = subprocess.Popen(["aplay", test],
                           shell=False, stderr=subprocess.PIPE)

Answer

QResource is only a resource that is known by Qt, so other technologies do not know how to handle the .qrc scheme, so in this case you must create a temporary file where you save the audio and aplay can use it:

import subprocess
from PySide2.QtCore import QFile, QFileInfo, QIODevice, QTemporaryFile
import application_rc


filename = ":///resources/sounds/LRMonoPhase4.wav"
file = QFile(filename)
fi = QFileInfo(file)
if file.open(QIODevice.ReadOnly):
    fp = QTemporaryFile("XXXXXX.{}".format(fi.completeSuffix()))
    if fp.open():
        fp.write(file.readAll())
        fp.seek(0)
        tmp_filename = fp.fileName()
        process = subprocess.Popen(
            ["aplay", "-vvv", tmp_filename], shell=False, stderr=subprocess.PIPE
        )
        process.communicate()

Note: If it is to be used within an application that uses the Qt eventloop then it is better to use QProcess than subprocess.Popen.

Leave a Reply

Your email address will not be published. Required fields are marked *