简体   繁体   中英

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 ie bash test.sh 1 . This gives this is y: 1 .

However, when the input is negative ie 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

Use a try/except that prints exception .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM