Gambit2007 Gambit2007 - 2 years ago 68
Bash Question

Best way to execute 'ls' shell command with multiple arguments?

I have the following command that I want to execute in Python and store in a variable:

ls -1 var1 2>/dev/null | grep var2 | grep var3 | head -n 1

But I can't get it to work. I tried using subprocess (both 'call' and 'check_output' as well as 'os.system' and nothing worked.. It always gave me an error or a wrong input, while when I execute this command in the shell it works properly.

Answer Source

For executing shell commands you'd use the subprocess module.

Usage and examples can be found at: Python Docs: subprocess

The actual python code for calling bash would look like this

import subprocess
task = subprocess.Popen("ls -1 var1 2>/dev/null | grep var2 | grep var3 | head -n 1",
directory =
print(directory) # result

The recommended way though would to use python to do the directory search. Python listdir() The command for oslistdir could look like this

files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download