bruce_ricard
bruce_ricard

Reputation: 771

Python long listing directory (ls -l), ls *

I'm trying to to a ls -l from python, to check for the last modification date of a file.

os.listdir doesn't show the long list format. subprocess.call shows the format, but actually prints it, and returns 0. I want to be able to put it in a variable. Any ideas ?

Also, I tried

subprocess.call("ls","*.py")

which answers

ls: cannot access *.py: No such file or directory

it works with shell=True, but if someone could explain why it doesn't work without it, I'll appreciate. If you know how to make it work, even better.

Upvotes: 6

Views: 12368

Answers (2)

Nic Scozzaro
Nic Scozzaro

Reputation: 7363

With nice formatting:

import subprocess
print(subprocess.check_output(['ls', '-lh']).decode('utf-8'))

Upvotes: 2

Amber
Amber

Reputation: 527133

It doesn't work without shell=True because the * is a shell expansion character - going from *.py to a list of files ending in .py is a function performed by the shell itself, not ls or python.

If you want to get the output of a command invoked via subprocess, you should use subprocess.check_output() or subprocess.Popen.

ls_output = subprocess.check_output(['ls', '-l'])

Upvotes: 8

Related Questions