Python子进程没有按预期为find命令工作

2024-06-01 00:19:31 发布

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

我试图找出python节点上的孤立文件。 下面是代码片段

#!/usr/bin/python
import subprocess
try:
        s = subprocess.check_output(["find", "/", "-fstype", "proc", "-prune", "-o", "\( -nouser -o -nogroup \)", "-print"])
except subprocess.CalledProcessError as e:
    print e.output
else:
    if len(s) > 0:
        print ("List of Orphan Files are \n%s\n" % s)
    else:
        print ("Orphan Files does not Exists on the NE")

当我尝试运行这个python代码时

> python test.py 
find: paths must precede expression: \( -nouser -o -nogroup \)
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

当我在CLI上运行相同的命令时,它工作正常。你知道吗

> find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print
/root/a

很少有人建议使用shell=true,因为根据python doc for subprocess,这是安全隐患。 Warning Using shell=True can be a security hazard.


Tags: 代码outputfilesprocfindshellelsesubprocess
3条回答

只需将shell=True添加到check\u输出中

s = subprocess.check_output(["find", "/", "-fstype", "proc", "-prune", "-o", "\( -nouser -o -nogroup \)", "-print"], shell=True)

我试了一下你的剧本,得到了和你一样的错误。我尝试了不同的方法,找到了适合我的方法。我变了

-print

-exec

而且成功了。但我不知道为什么会这样。你知道吗

您应该在每个空格上拆分命令。最简单的方法是使用^{}

import shlex
import subprocess

cmd = shlex.split('find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print')
subprocess.check_output(cmd)

相关问题 更多 >