Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Communicating Python Exception to a shell script

I have a test.py python script which contains following code.

def f(x):
    if x < 0:
        raise Exception("negative number")

    else: 
        return x

I have written another shell script test.sh that runs the python function inside it. The code is as follows

#!/bin/bash
X=$1

y=$(python3 -c "from test import f; print(f(`echo $X`))")
echo this is y: $y

The shell script works fine when input is positive i.e bash test.sh 1. This gives this is y: 1.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, when the input is negative i.e bash test.sh -1. It gives a python traceback.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/user/test.py", line 4, in f
    raise Exception("negative number")
Exception: negative number
this is y:

Question: what changes should be made to avoid the above output (avoid printing traceback).

Expected output:

this is y: exception

>Solution :

Use a try/except that prints exception.

y=$(python3 -c "from test import f
try: print(f(`echo $X`))
except: print('exception')")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading