Python子进程调用不能使用grep

Python子进程调用不能使用grep

本文介绍了Python子进程调用不能使用grep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python子进程调用应该按命令原样运行,但是它在抱怨是否有管道.这是我的代码:

Python subprocess call is supposed to run as command as is, but it is complaining if there is a pipe in it. Here is my code:

#!/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,则效果很好.

I am able to run the script successfully. It is just the pipe and the arguments following it which is a problem. If I run sc query mysvrc | findstr STOPPED directly on command line it works fine.

我该如何使用它?请注意,我使用jython2.7运行此python脚本.我无法使用win32serviceutil,因为找不到模块win32serviceutil.

How can I get this to work? Note that I run this python script using jython2.7. I wasn't successful in using win32serviceutil because it couldn't find the module win32serviceutil.

推荐答案

如上所述, subprocess不能处理单个str输入和像|这样的shell元字符,除非shell=True .但是在这种情况下,您实际上根本不需要管道.您可以让Python进行过滤,并避免完全连接到findstr的管道:

As already stated, subprocess can't handle single str inputs and shell metacharacters like | unless shell=True. But in this case, you really don't need a pipe anyway. You can have Python do the filtering and avoid the pipe to findstr completely:

# 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")

这篇关于Python子进程调用不能使用grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:18