Jananath Banuka
Jananath Banuka

Reputation: 633

Best way to check if a shell command has executed successfully

import os

val = os.popen("ls | grep a").read()

Let's say I want to check if a given directory has a any file named a. If the directory doesn't have a file with a in it the val is empty and if not val should be assigned with some output gotten from executing that command.

Are there any cases where the value of val could be still something even with empty output? In this case, there are no files with a but could val still have some value? Are there any cases where the output looks empty when we execute on a terminal, but value still has some value (e.g. white space)?

Is it an effective approach to use in general? (I am not really trying to check for files with certain names. This is actually just an example.)

Are there any better ways of doing such a thing?

Upvotes: 3

Views: 5170

Answers (2)

Chris Maes
Chris Maes

Reputation: 37832

I'd recommend using python3 subprocess, where you can use the check parameter. Then your command will throw an error if it does not succeed:

import subprocess
proc = subprocess.run(["ls | grep a"], shell=True, check=True, stdout=subprocess.PIPE)
# proc = subprocess.run(["ls | grep a"], shell=True, check=True, capture_output=True) # starting python3.7
print(proc.stdout)

but as @JohnKugelman suggested, in this case you'd better use glob:

import glob
files_with_a = glob.glob("*a*")

Upvotes: 2

AnsFourtyTwo
AnsFourtyTwo

Reputation: 2528

If you reallly go for the approach of running a os command from python, I'd recommend using the subprocess package:

import subprocess
command = "ls | grep a"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print(process.returncode)

Upvotes: 1

Related Questions