Subprocess run python arguments

Viewed 27

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?

1 Answers

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
]
Related