gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
How to get monitor resolution with Python in Linux via "hyprctl monitors" or "inxi"?
- User
How to get monitor resolution with Python in Linux via "hyprctl monitors" or "inxi"?
- Assistant
How to get monitor resolution with Python in Linux via "hyprctl monitors" or "inxi"?
To get the monitor resolution in Linux using Python, you have two options: using the hyprctl command or the inxi command.
Here is how you can do it for both methods.
hyprctlYou can use the subprocess module in Python to call the hyprctl monitors command and parse its output.
Here's an example:
import subprocess
import json
def get_monitor_resolutions_hyprctl():
# Run the command 'hyprctl monitors' and capture its output
result = subprocess.run(['hyprctl', 'monitors'],
capture_output=True,
text=True)
# Check for errors
if result.returncode != 0:
print("Error running hyprctl:", result.stderr)
return
# Parse the output (assuming it outputs in JSON format)
try:
monitors = json.loads(result.stdout)
resolutions = []
for monitor in monitors: # You may need to adjust this based on actual output structure
resolutions.append((monitor['name'], monitor['width'], monitor['height']))
return resolutions
except json.JSONDecodeError as e:
print("Could not decode JSON:", e)
resolutions = get_monitor_resolutions_hyprctl()
if resolutions:
for monitor in resolutions:
print(f"Monitor: {monitor[0]}, Resolution: {monitor[1]}x{monitor[2]}")
inxiYou can also retrieve monitor resolution using the inxi -G command with subprocess.
Here’s how to do it:
import subprocess
import re
def get_monitor_resolutions_inxi():
# Run the command 'inxi -G' and capture its output
result = subprocess.run(['inxi', '-G'],
capture_output=True,
text=True)
# Check for errors
if result.returncode != 0:
print("Error running inxi:", result.stderr)
return
# Print the output for debugging
print(result.stdout) # You can comment this out if you don't need to debug
resolutions = []
# Using regex to extract monitor resolutions from output
pattern = r'(\d+ x \d+)' # Example pattern, adjust as necessary
matches = re.findall(pattern, result.stdout)
for match in matches:
resolutions.append(match)
return resolutions
resolutions = get_monitor_resolutions_inxi()
if resolutions:
for res in resolutions:
print(f"Monitor Resolution: {res}")
hyprctl and inxi are installed and available in your PATH. You can typically install inxi via your package manager (sudo apt install inxi on Ubuntu/Debian, for example).hyprctl and inxi, so review that output first.