Python subprocess.run() 为: kill -HUP `ps -C gunicorn fch -o pid |头-n 1`

Python subprocess.run() to for: kill -HUP `ps -C gunicorn fch -o pid | head -n 1`

我需要一个 Python 脚本 subprocess.run() 调用如下:

kill -HUP `ps -C gunicorn fch -o pid | head -n 1`

这不能是一个长连接

subprocess.run(["kill","-HUP","ps","-C","gunicorn","fch","-o","pid","|","head","-n","1"])

如何将 ps -C gunicorn fch -o pid | head -n 1 部分读入 subprocess.run 以便 "kill","-HUP" 将其解释为带引号的字符串?

原始 shell 代码中的反引号为 ps 的调用创建了一个完整的独立子进程。管道实际上创建了另一个进程,for head!

如果你想在纯粹的 Python 中做到这一点(而不是将其全部委托给 shell),你可能想要至少进行一次额外的 subprocess 调用。您可能不需要 head,因为您可以轻松地在 Python.

中自己读取一行输出

试试这样的东西:

ps_process = subprocess.Popen(["ps","-C","gunicorn","fch","-o","pid"],
                              stdout=subprocess.PIPE)
pid_string = next(ps_process.stdout).decode().strip()
subprocess.run(["kill","-HUP", pid_string])

您也可以直接从 Python 发送 HUP 信号,而不是调用 kill 程序。哎呀,可能有一个模块可以让您查找其他 运行 程序的 PID。