Python 子进程调用不能使用 grep

Python subprocess call cannot take grep

Python 子进程调用应该按原样 运行 作为命令,但如果其中有管道,它就会抱怨。这是我的代码:

#!/usr/bin/python

import sys
import subprocess
import time
service_name= "mysrvc"
state ="STOPPED"
mycmd ="sc query " + service_name + " " + "|" + " findstr" + " " + state 
print(mycmd)
if subprocess.call(mycmd)==0:
  print("Service stopped successfully")

我得到的错误是:

ERROR: Invalid Option; Would you like to see help for the QUERY and QUERYEX commands? [ y | n ]:

如果我将命令更改为

mycmd = "sc query " + service_name 

我能够 运行 脚本成功。这只是管道和它后面的参数是一个问题。如果我直接在命令行上 运行 sc query mysvrc | findstr STOPPED 它工作正常。

我怎样才能让它工作?请注意,我 运行 这个 python 脚本使用 jython2.7。我没有成功使用 win32serviceutil,因为它找不到模块 win32serviceutil。

我不确定具体 jython,但是 subprocess 文档建议您的命令需要是列表,而不是字符串,除非您设置 shell 变量至 True。如果您将调用更改为 subprocess.call(mycmd, shell=True),您的代码应该可以工作,但请务必阅读文档中有关将 shell 设置为 True.[=21 所固有的安全风险的警告=]

如果您不想设置 shell=True,您将无法在命令中直接使用管道,但是文档中有一节 replacing shell pipeline 介绍了如何使用 subprocess.Popen.

模拟管道的功能

如前所述,subprocess can't handle single str inputs and shell metacharacters like | unless shell=True。但在这种情况下,你真的不需要管道。您可以让 Python 进行过滤并完全避免管道到 findstr

# sc query command only, as list which gets better safety/performance
mycmd = ["sc", "query", service_name]

# Open command to run asynchronously, capturing output
proc = subprocess.Popen(mycmd, stdout=subprocess.PIPE)

# Wait for process to complete while slurping output
stdout, _ = proc.communicate()

# Check if expected output was seen and process exited successfully
if state in stdout and proc.returncode == 0:
    print("Service stopped successfully")