python - 无法识别术语“Select-String”
问题描述
我试图通过运行这个 python 脚本来只获取 PID。
我目前的错误:
- 选择字符串未被识别为内部或外部命令
- 为了处理这个错误,我认为我需要逃避 | 通过添加 ^ --> 但显然它不起作用
我添加了一些 \ 来逃避“,希望它是正确的吗?
cmd = "netstat -ano | findstr " + str(o) print (cmd) cmd += " | Select-String \"TCP\s+(.+)\:(.+)\s+(.+)\:(\d+)\s+(\w+)\s+(\d+)\" | ForEach-Object { Write-Output $_.matches[0].Groups[6].value }" print (cmd) pid = run_command(cmd)
run_command 方法执行此操作:
def run_command(cmd_array,os_name='posix'):
p = subprocess.Popen(cmd_array,shell=True,cwd=os.getcwd())
output,err = p.communicate()
print('output=%s'%output)
print('err=%s'%err)
return output
预期结果
当我在命令提示符下单独运行命令时,它给了我 PID --> 在这种情况下为 7556。不太清楚为什么它不适用于脚本,而是单独在命令提示符下工作。
解决方案
这个问题特定于 Windows 操作系统
回答我自己的问题
- 在评论的帮助下,我没有使用我的 run_command 方法,因为它使用的是 shell = True。
shell = True 指的是 Windows 上的 cmd.exe,而不是 powershell。我写的命令是powershell命令。
- 直接使用 subprocess.call 运行 powershell 命令
Python 脚本
cmd = "netstat -ano | findstr 8080"
cmd += " | Select-String \"TCP\s+(.+)\:(.+)\s+(.+)\:(\d+)\s+(\w+)\s+(\d+)\" | ForEach-Object { Write-Output $_.matches[0].Groups[6].value }"
subprocess.call(["powershell.exe", cmd])
#this does the job but the code will print extra zeros along with PID. It was not what i was looking for.
结果:
6492(打印出 PID 以及一些额外的零)
什么对我有用 - 对于那些试图在 python 脚本中使用 PID 只获取 PID 和终止端口的人
cmd = "for /f \"tokens=5\" %a in ('netstat -aon ^| find \":8080"
cmd += "\" ^| find \"LISTENING\"\') do taskkill /f /pid %a"
#I added in some \ to escape the "
run_command(cmd)
结果:
成功:PID 2072 的进程已终止
推荐阅读
- c# - 瀑布结束问题。它提示回到其他对话框而不是结束
- google-bigquery - 在 BigQuery 中,是否可以在 BigQuery 存储过程中使用类似于 @@ROWCOUNT 的内容?
- javascript - 对于 D3 堆叠条,我如何知道鼠标在哪个条中?
- aws-code-deploy - AWS CodePloy 管道示例存储库:“bash: zip: command not found”
- ios - ScrollView 未显示自定义 UIView
- xamarin.forms - Xamarin 表单:如何为 StackLayout 添加 SwipeGestureRecognizer?
- javascript - 获取 TD 的值以在模态 Javascript 中显示
- python - [Python]如何自动为数据框分配特殊索引?
- java - 如何将不同的片段分配给不同的颜色表?
- tensorflow.js - TypeError: JSON 内容必须是 `dict`,但发现