Reputation: 3986
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.
Upvotes: 2
Views: 2359
Reputation: 30268
You need to ensure you are executing in a shell, as you are relying on the shell to dispatch the pipes, e.g. (Py>3.1):
import subprocess
var1, var2, var3 = "var1", "var2", "var3"
cmd = "ls -1 {} 2>/dev/null | grep {} | grep {} | head -n 1".format(var1, var2, var3)
result = subprocess.check_output(cmd, shell=True)
Upvotes: 0
Reputation: 56
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",
shell=True,
stdout=subprocess.PIPE)
directory = task.stdout.read()
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)]
Upvotes: 3
Reputation: 2553
I don't have any problem when using subprocess
:
>>> import subprocess
>>> sub = subprocess.Popen("ls -1 var1 2>/dev/null | grep var2 | grep var3 | head -n 1", shell=True, stdout=subprocess.PIPE)
>>> str = sub.stdout.read()
>>> str
''
You can find additional informations regarding calling shell command while saving the output here.
Hope it'll be helpful.
Upvotes: 1