• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python子进程调用不能使用grep

用户头像
it1352
帮助1

问题说明

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.

正确答案

#1

如上所述, 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")

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkehc
系列文章
更多 icon
同类精品
更多 icon
继续加载