简体   繁体   English

子进程运行 python arguments

[英]Subprocess run python arguments

If I run system_profiler SPDisplaysDataType | grep Resolution如果我运行system_profiler SPDisplaysDataType | grep Resolution system_profiler SPDisplaysDataType | grep Resolution in terminal, I get my resolution. system_profiler SPDisplaysDataType | grep 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.我试图用 subprocess.run 来做到这一点,但我不知道如何配置 arguments,我尝试了很多变体。 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但这与system_profiler SPDisplaysDataType运行相同, | grep Resolution | grep Resolution isn't working. | grep Resolution不起作用。 Does anyone know how to fix this?有谁知道如何解决这一问题?

What you want is to have shell=True :你想要的是有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.使用shell=True有其风险:当命令不受您的控制时(例如,您从用户输入中获取它),那么它就有可能破坏您的系统。 A less risky approach is to grep the lines yourself, which is not hard:一个风险较小的方法是 grep 自己的行,这并不难:

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

found = [
    line for line in res.stdout.splitlines()
    if "Resolution" in line
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM