subprocess ls examples / *没有fuch文件或目录

时间:2016-05-04 11:15:05

标签: python python-2.7 subprocess

>>> import subprocess
>>> child = subprocess.Popen(["ls", "examples/*"], stdout=subprocess.PIPE)
>>> ls: examples/*: No such file or directory

但是从终端开始工作

Beagle:kumarshubham$ ls examples/*
examples/convert_greyscale.py       examples/feat_det_harris_corner.py  examples/read_display_image.py
examples/example_set_roi.py     examples/manipulate_img_matplotlib.py   examples/remove_matplotlib_cache.py

可以指导我出错的地方吗?

4 个答案:

答案 0 :(得分:1)

import subprocess
child = subprocess.Popen(["cd /to-your-PATH/; ls", "examples/*"],shell=True, stdout=subprocess.PIPE)
child.stdout.read()

答案 1 :(得分:1)

这是因为(*)外卡使用。您需要提供shell = True才能通过shell解释器执行命令

>>> import subprocess
>>> child = subprocess.Popen(["ls", "examples/*"], stdout=subprocess.PIPE, shell=True)

答案 2 :(得分:1)

您应该在shell=True来电中添加Popen,即使*在您的情况下无效,ls examples/也应返回相同的输出:

child = subprocess.Popen(["ls", "examples/*"], stdout=subprocess.PIPE, shell=True)

另外,更多的pythonic方法可能是:

import os
os.listdir('examples')

答案 3 :(得分:1)

你可以使用额外的参数shell = True,然后它会看起来:

child = subprocess.Popen(["ls", "examples/*"], shell=True,  stdout=subprocess.PIPE)

NB!即使这样也行, - 根据官方python文档https://docs.python.org/2/library/subprocess.html使用shell = True可能是一个安全问题。