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")
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfkehc
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20