Python subprocess Popen: Why does “ls *.txt” not work? [duplicate]

大憨熊 提交于 2019-11-27 16:16:58

*.txt is expanded by your shell into file1.txt file2.txt ... automatically. If you quote *.txt, it doesn't work:

[~] ls "*.py"                                                                  
ls: cannot access *.py: No such file or directory
[~] ls *.py                                                                    
file1.py  file2.py file3.py

If you want to get files that match your pattern, use glob:

>>> import glob
>>> glob.glob('/etc/r*.conf')
['/etc/request-key.conf', '/etc/resolv.conf', '/etc/rc.conf']

You can pass the parameter shell to True. It will allow globbing.

import subprocess
p = subprocess.Popen('ls folder/*.txt',
                     shell=True,
                     stdout=subprocess.PIPE, 
                     stderr=subprocess.PIPE)
out, err = p.communicate()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!