aaa*_*aaa 3 python subprocess ls
我在看这个问题.
就我而言,我想做一个:
import subprocess
p = subprocess.Popen(['ls', 'folder/*.txt'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
Run Code Online (Sandbox Code Playgroud)
现在我可以在命令行上查看执行"ls文件夹/*.txt"的工作,因为该文件夹有很多.txt文件.
但在Python(2.6)中我得到:
ls:无法访问*:没有这样的文件或目录
我尝试过:
r'folder/\*.txt'
r"folder/\*.txt"
r'folder/\\*.txt'
和其他变化,但它似乎Popen不喜欢这个*角色.
有没有其他方法逃脱*?
*.txt由shell file1.txt file2.txt ...自动扩展.如果你引用*.txt,它不起作用:
[~] ls "*.py"
ls: cannot access *.py: No such file or directory
[~] ls *.py
file1.py file2.py file3.py
Run Code Online (Sandbox Code Playgroud)
如果要获取与模式匹配的文件,请使用glob:
>>> import glob
>>> glob.glob('/etc/r*.conf')
['/etc/request-key.conf', '/etc/resolv.conf', '/etc/rc.conf']
Run Code Online (Sandbox Code Playgroud)
您可以将参数shell传递给True.它将允许通配.
import subprocess
p = subprocess.Popen('ls folder/*.txt',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
Run Code Online (Sandbox Code Playgroud)