当我指定我们时,lsof命令不在指定的目录中查找

2024-04-20 06:06:23 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我写了一个python脚本,我的目标是使用lsof为本地用户列出特定目录(我的主文件夹)下所有打开的文件,并且只输出“uniq”条目。在

我的剧本是这样的:

import os, sys, getpass
user = getpass.getuser()
cmd = "lsof -u " + user + " +d ~ | sort | uniq"
os.system(cmd)

这种方法可以实现我想要它做的事情,它为当前本地用户执行lsof,但是它无法在我指定的主目录中进行具体查找。相反,它在根目录上执行lsof,并为用户列出整个文件系统的所有lsof。但是,当我执行相同的命令而不使用-u user时,它会在主目录中明确显示。我一直在研究这到底是为什么,是的,我尝试过使用+d /home/和{}而不是仅仅使用+d ~来实现这一点,所以我有点困惑。任何建议都很好:)


Tags: 文件目录脚本文件夹cmd目标os条目
2条回答

lsof使用或将选项连接在一起,在默认情况下,尝试将-a标志添加到和中。在

man page

Normally list options that are specifically stated are ORed - i.e., specifying the -i option without an address and the -ufoo option produces a listing of all network files OR files belonging to processes owned by user ''foo''.

有一些例外,但它们都不适用于你的情况。在

因此,-u me +d ~意味着“我或我的主目录中打开的所有文件。在

你怎么做你想做的?在

The -a option may be used to AND the selections. For example, specifying -a, -U, and -ufoo produces a listing of only UNIX socket files that belong to processes owned by user ''foo''.

在那里扔一个-a

cmd = "lsof -a -u " + user + " +d ~ | sort | uniq"

顺便说一句,通常情况下,您确实不想在Python中使用os.system,这就是为什么the documentation特别指出:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

实际上,为什么在Python中使用sortuniq而不是排序呢?或者,如果您只想运行这个shell管道,而不是用Python以任何方式处理它,那么为什么首先使用Python而不是bash?在

相关问题 更多 >