以一致的格式获取操作系统信息
就上下文而言,我目前使用 OS X,但我也有兴趣了解如何在 Linux 中解决这个问题。
很多情况下,我想查询一条信息,例如:
- 侦听特定端口的进程的ID。
- 特定进程正在使用的内存量。
- 与系统资源等相关的任何其他信息
。我可以使用 shell 命令(ps、lsof 等)相对轻松地实现这一点。
我的问题是这些命令总是返回一堵格式化文本,通常类似于表格。这对于快速终端命令来说很好。
然而,当我在应用程序开发中使用这些命令时,我必须对结果进行切片和切块才能获得我想要的确切信息。在某些情况下,结果的格式使得它们难以解析。
有没有一种方法可以查询操作系统信息,并以一致且易于解析的格式返回结果?例如,我会对类似于 CSV、JSON、XML 等的任何内容感到满意。
我希望答案不会是“事情就是这样”。
谢谢
For context, I currently use OS X, but I'm also interested to hear how this problem might be solved in Linux.
In many cases, I want to query a piece of info such as:
- ID of a process listening on a particular port.
- Amount of memory being used a particular process.
- Any other piece of info relating to system resources etc.
I can achieve this relatively easily using shell commands (ps, lsof, etc).
My problem is that these commands invariably return a wall of formatted text, usually resembling a table. That's fine for quick terminal commands.
However, when I use these commands in application development, I have to slice and dice the results to get the exact piece of info I'm after. In some cases, the results are formatted in such a way that makes them difficult to parse.
Is there a way to query OS info that returns results in a consistent and easy-to-parse format? For example, I'd be happy with anything similar to CSV, JSON, XML etc.
I'm hoping the answer won't be, "That's just the way it is".
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在Linux中,可以读取与进程相关的信息,并且可以将某些参数写入proc文件系统。您仍然需要解析以下结果
但我想这比从程序中执行 shell 命令更好。
了解更多细节。
In Linux, information related to a process can be read from and certain parameters can be written into the proc file system.You would still have to parse the results of
but I guess it's better than executing shell commands from your program.
for more details.