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
.
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
CodePudding user response:
Use a try/except
that prints exception
.
y=$(python3 -c "from test import f
try: print(f(`echo $X`))
except: print('exception')")