Search code examples
pythonoperating-systemsubprocessx11mpv

Command not executed on if statement being true


So I'm writing a simple program in Python that checks active window ID and in this program I have an if statement inside a while True loop that checks if the active window ID matches the expected window ID.

Here's the code:

import os, subprocess

def get_window_id():
    output = subprocess.check_output("xprop -root | grep \"window id\"", shell=True)
    get_window_id.result = {}

    for row in output.split(b"\n"):
        if b": " in row:
            key, value = row.split(b": ")
            get_window_id.result[key.strip(b"window id # ")] = value.strip()

while True:
    get_window_id()
    print(get_window_id.result[b"_NET_ACTIVE_WINDOW(WINDOW)"].strip(b"b'window id # "))

    if get_window_id.result[b"_NET_ACTIVE_WINDOW(WINDOW)"].strip(b"b'window id # ") != "b'0x3000003'":
        os.system("kill -STOP $(pgrep mpv)")
    else:
        os.system("kill -CONT $(pgrep mpv)")

When the active window ID doesn't match the expected one, the block of code that corresponds to that condition executes, but when the active window ID matches the expected one, the block of code that corresponds to that condition doesn't execute. I obviously want that block of code to execute.

As you can see, I'm not the best at Python and asking for help but I hope that this is enough for somebody to help. If not I can always provide more information :)

And sorry if the title and/or body of the question are not clear. It's currently 2AM and I've been trying to do this all day.

Thanks in advance.


Solution

  • YES! I did it! Just needed some sleep and a little bit more searching, but basically what I needed to do is get rid of those bs before the strings and to do that I needed to add encoding=utf8 to the subprocess.check_output line and delete the bs and it worked!

    Code after the change:

    import os, subprocess
    
    def get_window_id():
        output = subprocess.check_output("xprop -root | grep \"window id\"", shell=True, encoding="utf8")
        get_window_id.result = {}
    
        for row in output.split("\n"):
            if ": " in row:
                key, value = row.split(": ")
                get_window_id.result[key.strip("window id # ")] = value.strip()
    
    while True:
        get_window_id()
        print(get_window_id.result["_NET_ACTIVE_WINDOW(WINDOW)"].strip("'window id # "))
    
        if get_window_id.result["_NET_ACTIVE_WINDOW(WINDOW)"].strip("'window id # ") != "0x3000003":
            os.system("kill -STOP $(pgrep mpv)")
        else:
            os.system("kill -CONT $(pgrep mpv)")