1

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
2
  • 2
    The shell knows nothing about exceptions. What it does know is that the program "failed" if the exit status is not 0. Python will have a non-zero exit status if it terminates due to an uncaught exception, but the exception itself does not pass from the Python script to the shell script. (The shell could try to parse the standard error to allow some logic around the contents of the trace back, but if the specific exception is important, then you should catch the exception and exit with a specific exit code.) Commented Jun 25, 2022 at 16:44
  • 2
    And do not use command substitution, etc, to construct the Python script. Pass the value of X as an argument to the script, something like python3 -c 'from test import f; import sys; print(f(sys.argv[1]))' "$X". Commented Jun 25, 2022 at 16:45

1 Answer 1

2

Use a try/except that prints exception.

y=$(python3 -c "from test import f
try: print(f(`echo $X`))
except: print('exception')")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.