Python's subprocess module returning different results from Unix shell

后端 未结 4 1162
灰色年华
灰色年华 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:30

    Why not use glob instead? It's going to be faster than "shelling out"!

    import glob
    glob.glob('*.csv')
    

    This gives you just the names, not all the extra info ls -l supplies, though you can get extra info with os.stat calls on files of interest.

    If you really must use ls -l, I think you want to pass it as a string for the shell to do the needed star-expansion:

    proc = sp.Popen('ls -l *.csv', shell=True, stdout=sp.PIPE)
    

提交回复
热议问题