[英]Usage of subprocess.check_output() for searching files inside python
I am using subprocess.check_output() to run the basic "ls" command. 我正在使用subprocess.check_output()运行基本的“ ls”命令。 From what I understand after reading documentation is that this process can help run a shell command from within the domain of python. 根据我阅读文档后的了解,该过程可以帮助从python域内运行shell命令。
Let us say my example folder is home/ where I have the following files 假设我的示例文件夹是home /,其中有以下文件
-rw-rw-r-- 1 aravind aravind 761 Dec 2 10:48 flux_acis_bare_479.dat
-rw-rw-r-- 1 aravind aravind 2426 Dec 2 10:49 flux_acis_bare_481.dat
-rw-rw-r-- 1 aravind aravind 759 Dec 2 18:46 flux_acis_hetg_479.dat
-rw-rw-r-- 1 aravind aravind 2178 Dec 2 18:45 flux_acis_hetg_481.dat
If I do an ls search from shell for the keyword "acis", naturally all files are returned. 如果我从shell进行ls搜索以搜索关键字“ acis”,则自然会返回所有文件。
Now I want to do the same thing from within python. 现在我想在python中做同样的事情。
The following is my attempt 以下是我的尝试
import os
import subprocess
os.chdir("home/")
subprocess.check_output(["ls", "*acis*"])
The two " ", " " should run sequentially and I should get back all the files as a result would have been my guess. 这两个“”,“”应按顺序运行,我应该取回所有文件,结果是我的猜测。 However the output I get is a file not found error. 但是我得到的输出是找不到文件错误。
Command '['ls', '*acis*']' returned non-zero exit status 2
Disclaimer : I have looked at multiple Stack Overflow questions on subprocess.check_output() and tried to see if my question is a duplicate. 免责声明:我在subprocess.check_output()上查看了多个Stack Overflow问题,并尝试查看我的问题是否重复。 If I have missed something please let me know. 如果我错过了什么,请告诉我。
As @Ry-♦ said, glob
is the module you're looking for. 正如@ Ry-♦所说, glob
是您要查找的模块。 Running glob.glob("home/*acis*")
will give you a list of files and directories that match the pattern. 运行glob.glob("home/*acis*")
将为您提供与该模式匹配的文件和目录的列表。 To match recursively, like if you wanted to find a file such as home/flux_acis_folder/something_else.dat
, you could use glob.glob("home/*acis**", recursive=True)
. 要进行递归匹配,例如,如果您想查找诸如home/flux_acis_folder/something_else.dat
类的文件,则可以使用glob.glob("home/*acis**", recursive=True)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.