1

If I run system_profiler SPDisplaysDataType | grep Resolution in terminal, I get my resolution. I was trying to do this with subprocess.run, but I didn't know how to configure the arguments and I tried many variations. My code is like this:

res = subprocess.run(["system_profiler", "SPDisplaysDataType", "|", "grep", "Resolution"], capture_output=True)

but this is running the same as system_profiler SPDisplaysDataType, the | grep Resolution isn't working. Does anyone know how to fix this?

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • Does this answer your question? [How to use \`subprocess\` command with pipes](https://stackoverflow.com/questions/13332268/how-to-use-subprocess-command-with-pipes) – mkrieger1 Aug 12 '22 at 20:33

1 Answers1

0

What you want is to have shell=True:

res = subprocess.run("system_profiler SPDisplaysDataType | grep Resolution", shell=True, encoding="utf-8", capture_output=True)
print(res.stdout)

Using shell=True has its risk: when the command was not under your control (for example, you get it from user input), then there is a chance that it could break your system. A less risky approach is to grep the lines yourself, which is not hard:

res = subprocess.run(
    ["system_profiler", "SPDisplaysDataType"],
    encoding="utf-8", capture_output=True,
)

found = [
    line for line in res.stdout.splitlines()
    if "Resolution" in line
]
Hai Vu
  • 37,849
  • 11
  • 66
  • 93