Python's subprocess module returning different results from Unix shell

后端 未结 4 1128
灰色年华
灰色年华 2021-01-13 01:34

I\'m trying to get a list of the CSV files in a directory with python. This is really easy within unix:

ls -l *.csv

And, predictably, I get

4条回答
  •  有刺的猬
    2021-01-13 02:23

    If you want it to behave as it does at the shell, you need to pass shell=True (your mileage may vary here, depending on your system and shell). In your case the problem is that when you do ls -l *.csv, the shell is evaluating what * means, not ls. (ls is merely formatting your results, but the shell has done the heavy lifting to determine what files match *.csv). Subprocess makes ls treat *.csv literally, and look for a file with that specific name, which of course there aren't any (since that's a pretty hard filename to create).

    What you really should be doing is using os.listdir and filtering the names yourself.

提交回复
热议问题