python 检查输出查找命令不工作

python check output find command not working

我正在尝试从插入 raspberry pi 的 USB 闪存驱动器中找到名为 'config.txt' 的文件的路径。使用的物理驱动器可能并不总是相同的,因此路径可能并不总是相同的。所以我使用

'find /media/pi/*/config.txt' 

在终端中找到路径并且工作正常。 现在我去使用 check_output 并获得一串巨大的路径。

from subprocess import check_output
cmd = ['find', '/media/pi/*/config.txt']
out = check_output(cmd,shell=True) 

根据https://docs.python.org/2/library/subprocess.html

,我将 shell 设置为 True 以允许通配符

out 的结果是:

'.\n./.Xauthority\n./.xsession-errors\n./Public\n./.dmrc\n./Downloads\n./test.sh\n./.idlerc\n./.idlerc/recent-files.lst\n./.idlerc/breakpoints.lst\n./.asoundrc\n./.bash_logout\n./.profile\n./Templates\n./Music\n./.bash_history\n./Videos\n./.local\n./.local/share\n./.local/share/gvfs-metadata\n./.local/share/gvfs-metadata/home\n./.local/share/gvfs-metadata/home-d6050e94.log\n./.local/share/applications\n./.local/share/recently-used.xbel\n./.local/share/Trash\n.....

而且还会持续一段时间。 我尝试查看其他几个类似的问题,包括下面的 link,但没有运气。

Store output of subprocess.Popen call in a string

由于您使用的是 shell=True,因此您可以使用以下内容:

from subprocess import check_output
cmd = 'cd /media/pi && find . -iname config.txt'
out = check_output(cmd, shell=True) 

尽可能避免使用通配符,在搜索目标文件之前更改当前工作目录即可。

如果您想使用通配符,您需要传递一个字符串,就像您从 shell 传递一样:

from subprocess import check_output
cmd = 'find /media/pi/*/config.txt'
out = check_output(cmd,shell=True)

你实际上根本不需要子进程,glob 会做你想做的事:

from glob import glob 
files =  glob('/media/pi/*/config.txt')