使用 python os.system 从 netstat 中提取端口并在变量中使用它

问题描述

我正在寻找一种从 netstat 中提取端口并将其用作变量的解决方案。 问题是当我打印它时,值是 0 虽然当我在 bash 中使用相同的命令时它返回正确的端口。

device_port = os.system("netstat -atnp 2>/dev/null | awk '/adb/ {print $4}' | cut -d ':' -f 2")

返回值 5037

print(device_port)

返回值 0

我不知道为什么会这样。

谢谢

解决方法

您的第一个命令不会返回 5037,而是打印 5037。这是不同的。

查看os.system的文档:https://docs.python.org/3/library/os.html#os.system

它声明它将把命令的标准输出转发到控制台,并返回命令的退出代码

这正是发生的事情,您的代码将 5037 打印到控制台并返回 0 表示命令成功。


修复:

使用 subprocess 而不是 os.system。甚至在 os.system 的官方文档中也推荐了它。这将允许您捕获输出并将其写入变量:

import subprocess

command = subprocess.run("netstat -atnp 2>/dev/null | awk '/adb/ {print $4}' | cut -d ':' -f 2",check=True,# Raise an error if the command failed
    capture_output=True,# Capture the output (can be accessed via the .stdout member)
    text=True,# Capture output as text,not as bytes
    shell=True)  # Run in shell. Required,because you use pipes.
    
device_port = int(command.stdout)  # Get the output and convert it to an int
print(device_port)  # Print the parsed port number

这是一个工作示例:https://ideone.com/guXXLl

我用 id -u 替换了您的 bash 命令,因为您的 bash 脚本没有在 ideome 上打印任何内容,因此 int() 转换失败。