In case some command we try to execute is not found on the server or a specific error from a command output.
For example:
#!/usr/bin/env python3
import subprocess
os_cmd = 'ech hello'
subprocess.Popen(os_cmd, shell=True)
Error output is:
/bin/sh: 1: ech: not found
How to write exception specific for such command not found error instead of such Built-in Exceptions or instead of just checking only the return code zero or non-zero?
Or is the only way to do it in a dirty way as follows?
#!/usr/bin/env python3
import subprocess
os_cmd = 'ech hello'
p1 = subprocess.Popen(os_cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p1.communicate()
exit_code = p1.poll()
if exit_code != 0:
string = stderr.decode()
substring = "not found"
if substring in string:
print("It is command not found error")
print("Do some solution...")
else:
print("Command succeeded")
out = stdout.decode().strip().split()[0]
print(out)
Output:
It is command not found error
Do some solution...