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

But from terminal it works

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

Can one guide me where i am going wrong?

Hackaholic
  • 19,069
  • 5
  • 54
  • 72

4 Answers4

1
import subprocess
child = subprocess.Popen(["cd /to-your-PATH/; ls", "examples/*"],shell=True, stdout=subprocess.PIPE)
child.stdout.read()
Ohad the Lad
  • 1,889
  • 1
  • 15
  • 24
1

This is because of (*) wild card usage. You need to supply shell=True to execute the command through shell interpreter

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

You should add shell=True in your Popen call even if * is useless in your case, ls examples/ should return the same output:

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

Plus, more pythonic approach could be:

import os
os.listdir('examples')
mvelay
  • 1,520
  • 1
  • 10
  • 23
1

you can use additional parameter shell=True, then it would look:

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

NB! even this will work, - according to official python documentation https://docs.python.org/2/library/subprocess.html using shell=True might be a security issue.

Drako
  • 773
  • 10
  • 22